我想知道是否可以在打字稿中确定对象的类型。请考虑以下示例:
type T = [number, boolean];
class B {
foo: T = [3, true];
bar(): boolean {
return this.foo instanceof T;
}
}
Run Code Online (Sandbox Code Playgroud)
typeof运算符似乎不是解决方案,instanceof也是如此。
简答
(几乎)所有类型信息都在编译后被删除,并且您不能将instanceof操作符与运行时不存在的操作数(T在您的示例中)一起使用。
长答案
TypeScript 中的标识符可以属于以下一个或多个组:type、value、namespace。作为 JavaScript 发出的是value组中的标识符。
因此运行时操作符只适用于values。因此,如果您想对 的值进行运行时类型检查foo,您需要自己进行艰苦的工作。
有关更多信息,请参阅此部分:http : //www.typescriptlang.org/Handbook#declaration-merging
添加到@vilcvane的答案:types并interfaces在编译期间消失,但一些class信息仍然可用。因此,例如,这是行不通的:
interface MyInterface { }
var myVar: MyInterface = { };
// compiler error: Cannot find name 'MyInterface'
console.log(myVar instanceof MyInterface);
Run Code Online (Sandbox Code Playgroud)
但这确实:
class MyClass { }
var myVar: MyClass = new MyClass();
// this will log "true"
console.log(myVar instanceof MyClass);
Run Code Online (Sandbox Code Playgroud)
但是,值得注意的是,即使您的代码编译没有错误,这种测试也可能会产生误导:
class MyClass { }
var myVar: MyClass = { };
// no compiler errors, but this logs "false"
console.log(myVar instanceof MyClass);
Run Code Online (Sandbox Code Playgroud)
如果您查看 TypeScript 如何在每个示例中生成输出 JavaScript,这是有道理的。
| 归档时间: |
|
| 查看次数: |
5737 次 |
| 最近记录: |