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
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
| 归档时间: |
|
| 查看次数: |
260236 次 |
| 最近记录: |