我想知道是否有可能在typescript中确定对象的类型。请考虑下面的示例:
type T = [number, boolean];
class B {
foo: T = [3, true];
bar(): boolean {
return this.foo instanceof T;
}
}typeof运算符似乎不是一种解决方案,instanceof也不是。
发布于 2016-03-02 21:41:25
Short answer
(几乎)所有类型信息在编译后都会被删除,并且您不能将instanceof运算符与在运行时不存在的操作数(在您的示例中为T)一起使用。
Long answer
TypeScript中的标识符可以属于以下一个或多个组:类型、值、命名空间。作为JavaScript发出的是值组中的标识符。
因此,运行时运算符仅适用于值。因此,如果您想要对foo的值进行运行时类型检查,则需要自己完成这项艰巨的工作。
有关详细信息,请参阅TypeScript手册的Declaration Merging部分。
发布于 2016-03-02 23:02:55
补充到@vilcvane的答案是:types和interfaces在编译过程中消失了,但是一些class信息仍然可用。
interface MyInterface { }
var myVar: MyInterface = { };
// compiler error: Cannot find name 'MyInterface'
console.log(myVar instanceof MyInterface);但这确实是:
class MyClass { }
var myVar: MyClass = new MyClass();
// this will log "true"
console.log(myVar instanceof MyClass);但是,重要的是要注意,这种测试可能会产生误导,即使您的代码编译时没有错误:
class MyClass { }
var myVar: MyClass = { };
// no compiler errors, but this logs "false"
console.log(myVar instanceof MyClass);This makes sense if you look at how TypeScript is generating the output JavaScript in each of these examples。
https://stackoverflow.com/questions/35745895
复制相似问题