TypeScript中的类类型检查

在ActionScript中,可以在运行时使用是运营商检查类型:

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

是否有可能检测一个变量(扩展或)是TypeScript的某个类或接口?

我在语言规范里找不到任何关于它的信息。在处理类/接口时,它应该存在。

731510 次浏览
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 < / p >

你可以为此使用instanceof操作符。中数:

实例运算符测试对象的原型属性是否为

.构造函数出现在对象原型链的任何位置

如果你不知道原型和原型链是什么,我强烈建议你去查一下。这里还有一个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
    

本例中的原型链为:

动物。Object.prototype

你有两种支票

通过ex, isString检查可以像这样执行:

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

尽管已经有了一些好的答案。@Gilad提出的解决方案有缺陷,如果分配的内容swim存在类型,但值设置为undefined。一个更有力的检查应该是:

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

这个解决方案不依赖于swim的值!