TypeScript 中的类类型检查 [英] Class type check in TypeScript

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

问题描述

在 ActionScript 中,可以在运行时使用 是运算符:

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

是否可以使用 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 运算符

instanceof 运算符要求左操作数为 Any 类型、对象类型或类型参数类型,右操作数为 Any 类型或函数"的子类型接口类型.结果总是布尔基元类型.

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.

另见:

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

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