使用TypeScript检查类类型 [英] Class type check with TypeScript

查看:327
本文介绍了使用TypeScript检查类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm very excited about TypeScript, so I started to play with it. As an Actionscript developer, it makes Javascript less hard.

但是,在Actionscript中,可以使用是运营商

However, 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 
trace(mySprite is DisplayObject);// true 
trace(mySprite is IEventDispatcher); // true

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

Is it possible to detect if a variable (extends or) is a certain class or interface with TypeScript? I couldn't find anything about it in the language specs, it should be there when working with classes/interfaces.

推荐答案


4.19.4实例运算符



instanceof 运算符要求左操作数为Any类型,对象类型,或类型参数类型,右操作数是Any类型或'Function'接口类型的子类型。结果始终是布尔基元类型。

4.19.4 The instanceof operator

The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the 'Function' interface type. The result is always of the Boolean primitive type.

所以你可以使用

mySprite instanceof Sprite;

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

Note that this operator is also in ActionScript but it shouldn't be used there anymore:


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

The is operator, which is new for ActionScript 3.0, allows you to test whether a variable or expression is a member of a given data type. In previous versions of ActionScript, the instanceof operator provided this functionality, but in ActionScript 3.0 the instanceof operator should not be used to test for data type membership. The is operator should be used instead of the instanceof operator for manual type checking, because the expression x instanceof y merely checks the prototype chain of x for the existence of y (and in ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance hierarchy).

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

TypeScript's instanceof shares the same problems. As it is a language which is still in its development I recommend you to state a proposal of such facility.

参见:

  • MDN: instanceof

这篇关于使用TypeScript检查类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆