TypeScript中的类类型检查


240

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

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

是否可以使用TypeScript检测变量(扩展或)是否为某个类或接口?

我在语言规范中找不到任何有关它的信息。使用类/接口时,它应该在那里。

Answers:


318

4.19.4 instanceof运算符

instanceof操作者需要的左操作数是类型的任何,对象类型,或类型参数类型和右操作数是任何类型或“功能”接口类型的子类型的。结果始终是布尔基元类型。

所以你可以使用

mySprite instanceof Sprite;

请注意,该运算符也位于ActionScript中,但现在不应再在其中使用:

is运算符是ActionScript 3.0的新增功能,它使您能够测试变量或表达式是否是给定数据类型的成员。在早期版本的ActionScript中,instanceof运算符提供了此功能,但在ActionScript 3.0中,不应将instanceof运算符用于测试数据类型成员身份。手动类型检查应使用is运算符,而不是instanceof运算符,因为表达式x instanceof y只是检查x的原型链是否存在y(并且在ActionScript 3.0中,原型链无法提供的完整图片继承层次结构)。

TypeScript instanceof存在相同的问题。由于这是一种仍在发展中的语言,因此我建议您陈述有关此功能的建议。

也可以看看:


54

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


29
这不是运行时类型检查,而只是检查对象是否具有特定属性。这对于联合类型可能很好,因此可以在此特定情况下使用,但实际上无法为所有此类事件创建“ isThingy”。此外,如果鱼和鸟都能游泳,那么您注定会失败。我很高兴我使用HAXE具有可靠的类型检查,所以你可以做的Std.is(pet, Fish),它在类型的作品,接口等
马克Knol的

4
我发现此答案很有帮助,但我认为您可以对其进行调整,使其更加精确。在isFish本身所创建的断言,它的身体没有成为一个班轮谓语。这样做的好处是,编译器在编译时理解适当的可能函数,但是内部的代码isFish在运行时执行。您甚至可以让防护包含一条instanceof语句,例如return pet instanceof Fish(假设它是一个类,而不是一个接口),但这是不必要的,因为编译器可以instanceof直接理解。

4
这也称为“用户定义类型防护
朱利安(Julian)

@MarkKnol实际上是运行时检查,但打字稿也具有理解推断类型的能力(意味着:您可以相信我,它会是X或Y类型,因为我会在运行时对其进行测试)。
Flavien Volken '18

3
您可能要考虑使用,(pet as Fish)因为tslinter会抱怨(<Fish>pet)。请参阅tslint文档
Bryan

1

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

instanceof运算符测试构造函数的prototype属性是否出现在对象的原型链中的任何位置。

如果您不知道什么是原型和原型链,我强烈建议您进行查找。这也是一个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
    
    

本示例中的原型链为:

动物>动物原型>对象原型

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.