我用谷歌搜索了最后一小时,我没有找到一个很好的答案或解释我的问题.
我有一个成员变量定义为联合类型,基元(数字)或接口(KnockoutObservable),我不能使用instanceof或typeof typeguards而不会产生错误.我正在使用带有Typescript 1.4的VS2013更新4.我已经设置了几个例子来证明这个问题:
class foo {
foo() {}
}
class bar {
bar() {}
}
interface baz {
baz();
}
// This case breaks
var var1: number|foo;
if (typeof var1 === "number") {
var1 = 5;
}
// Generates error "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."
else if (var1 instanceof foo) {
var1.foo();
}
// This also breaks, same error as above
if (var1 instanceof number) …Run Code Online (Sandbox Code Playgroud)