programing

TypeScript에서 클래스 유형 확인

css3 2023. 3. 1. 11:24

TypeScript에서 클래스 유형 확인

ActionScript에서는 is 연산자를 사용하여 런타임에 유형을 확인할 수 있습니다.

var mySprite:Sprite = new Sprite(); 
trace(mySprite is Sprite); // true 
trace(mySprite is DisplayObject);// true 
trace(mySprite is IEventDispatcher); // true

변수(확장 또는 확장)가 TypeScript와의 특정 클래스 또는 인터페이스인지 여부를 검출할 수 있습니까?

언어 사양에서는 아무것도 찾을 수 없었습니다.클래스/인터페이스를 조작할 때는, 거기에 있을 필요가 있습니다.

4.19.4 운영자의 인스턴스

instanceof연산자를 사용하려면 왼쪽 피연산자가 유형 Any, 객체 유형 또는 유형 매개 변수 유형이어야 하며 오른쪽 피연산자는 유형 Any 또는 '기능' 인터페이스 유형의 하위 유형이어야 합니다.결과는 항상 Boolean 원시 유형입니다.

그래서 당신은 사용할 수 있다

mySprite instanceof Sprite;

이 연산자는 ActionScript에도 있지만 더 이상 이 연산자를 사용할 수 없습니다.

is 연산자는 ActionScript 3.0에서 새로 추가된 연산자로 변수 또는 식이 지정된 데이터 유형의 멤버인지 테스트할 수 있습니다.이전 버전의 ActionScript에서는 instanceof 연산자가 이 기능을 제공했지만 ActionScript 3.0에서는 instanceof 연산자를 사용하여 데이터 유형 구성원 자격을 테스트해서는 안 됩니다.표현식 x instance of y는 x의 프로토타입 체인에 y의 존재 여부만 체크하기 때문에 수동 타입 체크에는 instanceof 연산자 대신 is 연산자를 사용해야 합니다(ActionScript 3.0에서는 프로토타입 체인은 상속 계층의 완전한 그림을 제공하지 않습니다).

TypeScript의instanceof는 같은 문제를 공유하고 있습니다.아직 개발 중인 언어이기 때문에, 그러한 설비의 제안을 하는 것을 추천합니다.

다음 항목도 참조하십시오.

TypeScript에는 런타임에 변수 유형을 검증하는 방법이 있습니다.형식 술어를 반환하는 검증 함수를 추가할 수 있습니다.따라서 if 문 안에서 이 함수를 호출하여 해당 블록 내의 모든 코드를 사용자가 생각하는 유형으로 사용해도 안전한지 확인할 수 있습니다.

TypeScript 문서의 예:

function isFish(pet: Fish | Bird): pet is Fish {
   return (<Fish>pet).swim !== undefined;
}

// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
  pet.swim();
}
else {
  pet.fly();
}

자세한 것은, https://www.typescriptlang.org/docs/handbook/advanced-types.html 를 참조해 주세요.

를 사용할 수 있습니다.instanceof오퍼레이터에게 문의해 주세요.MDN에서:

instance of 연산자는 생성자의 프로토타입 속성이 객체의 프로토타입 체인에 있는지 여부를 테스트합니다.

시제품과 시제품 체인이 무엇인지 모르는 경우 찾아보기를 강력히 권장합니다.또한 개념을 명확히 할 수 있는 JS(TS는 이 점에서 유사)의 예를 다음에 제시하겠습니다.

    class Animal {
        name;
    
        constructor(name) {
            this.name = name;
        }
    }
    
    const animal = new Animal('fluffy');
    
    // true because Animal in on the prototype chain of animal
    console.log(animal instanceof Animal); // true
    // Proof that Animal is on the prototype chain
    console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true
    
    // true because Object in on the prototype chain of animal
    console.log(animal instanceof Object); 
    // Proof that Object is on the prototype chain
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true
    
    console.log(animal instanceof Function); // false, Function not on prototype chain
    
    

이 예의 원형 체인은 다음과 같습니다.

animal > Animal.protype > Object.protype

두 가지 유형의 수표가 있습니다.

의해 ex에 ex에 의해isString검사는 다음과 같이 수행할 수 있습니다.

function isString(value) {
    return typeof value === 'string' || value instanceof String;
}

비록 늦었지만 이미 몇 가지 좋은 답이 존재한다.@된 내용이 @Gilad에 있는 경우 .swim[으로 존재하지만 [가 [Type]으로 되어 있습니다.undefined하다

export const isFish= (pet: Fish | Bird): pet is Fish =>
   Object.keys(pet).includes('swim');

of of of of of this this 、 this this this this this this this 。swim!

언급URL : https://stackoverflow.com/questions/12789231/class-type-check-in-typescript