我对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的某个类或接口?我在语言规范中找不到任何关于它的东西,在使用类/接口时它应该存在.
我写了这段代码
interface Foo {
abcdef: number;
}
let x: Foo | string;
if (x instanceof Foo) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是TypeScript给了我这个错误:
'Foo' only refers to a type, but is being used as a value here.
Run Code Online (Sandbox Code Playgroud)
为什么会这样?我认为instanceof可以检查我的值是否具有给定类型,但TypeScript似乎不喜欢这样.