使用TypeScript检查类类型

Mar*_*nol 203 typechecking typescript

我对TypeScript感到非常兴奋,所以我开始玩它.作为一个Actionscript开发人员,它使Javascript变得不那么难了.

但是,在Actionscript中,可以使用is运算符在运行时检查类型:

var mySprite:Sprite = new Sprite(); 
trace(mySprite is Sprite); // true 
trace(mySprite is DisplayObject);// true 
trace(mySprite is IEventDispatcher); // true
Run Code Online (Sandbox Code Playgroud)

是否可以检测变量(extends或)是否是TypeScript的某个类或接口?我在语言规范中找不到任何关于它的东西,在使用类/接口时它应该存在.

Zet*_*eta 270

4.19.4 instanceof运算符

instanceof操作者需要的左操作数是任何类型,对象类型,或者类型参数的类型,并且将右操作数是任何类型或"功能"接口类型的子类型的.结果始终是布尔基元类型.

所以你可以使用

mySprite instanceof Sprite;
Run Code Online (Sandbox Code Playgroud)

请注意,此运算符也在ActionScript中,但不应再在那里使用:

is运算符是ActionScript 3.0的新增功能,它允许您测试变量或表达式是否是给定数据类型的成员.在以前版本的ActionScript中,instanceof运算符提供了此功能,但在ActionScript 3.0中,不应使用instanceof运算符来测试数据类型成员资格.应该使用is运算符而不是instanceof运算符进行手动类型检查,因为表达式x instanceof y只检查x的原型链是否存在y(并且在ActionScript 3.0中,原型链不提供完整的图片继承层次结构).

TypeScript instanceof有同样的问题.由于这是一种仍处于开发阶段的语言,我建议您说明此类设施的提案.

也可以看看:


小智 41

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();
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请访问:https: //www.typescriptlang.org/docs/handbook/advanced-types.html

  • 这不是运行时类型检查,它只是检查对象是否具有某个属性.对于联合类型来说这可能很好,所以适用于这个特定的情况,但它不是真的可以为这样的一切创建"isThingy".如果鱼和鸟都游泳你就注定要失败.我很高兴我正在使用具有可靠类型检查的Haxe,因此你可以做`Std.is(pet,Fish)`,它适用于类型,接口等. (20认同)
  • 这也称为"用户定义类型警卫",请参阅https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html (4认同)
  • 我觉得这个答案很有帮助,但我认为你可以调整一下来更准确一点.`isFish`本身是创建的谓词,它的主体不必是单行谓词.这样做的好处是编译器在编译时能够理解适当的可能函数,但是`isFish`中的代码是在运行时执行的.你甚至可以让守卫包含一个`instanceof`语句,例如`return pet instanceof Fish`(假设它是一个类而不是接口),但这是不必要的,因为编译器直接理解`instanceof`. (3认同)
  • 您可能要考虑使用`(pet as Fish)`,因为tslinter会抱怨`(&lt;Fish&gt; pet)`。参见[tslint doc](https://palantir.github.io/tslint/rules/no-angle-bracket-type-assertion/) (2认同)

Ser*_*rge 15

您有两种类型的支票

例如,isString检查可以这样执行:

function isString(value) {
    return typeof value === 'string' || value instanceof String;
}
Run Code Online (Sandbox Code Playgroud)


Wil*_*een 13

您可以instanceof为此使用运算符。来自 MDN:

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
    
    
Run Code Online (Sandbox Code Playgroud)

本例中的原型链为:

动物 > Animal.prototype > Object.prototype