Class type check in TypeScript

前端 未结 3 1075
星月不相逢
星月不相逢 2020-11-30 00:28

In ActionScript, it is possible to check the type at run-time using the is operator:

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


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 00:54

    You can use the instanceof operator for this. From MDN:

    The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

    If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:

        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
        
        

    The prototype chain in this example is:

    animal > Animal.prototype > Object.prototype

提交回复
热议问题