【发布时间】:2016-09-06 07:19:56
【问题描述】:
如果我正在编写用户定义的类型保护,如下所示:
interface Cat {
meow: () => void;
}
function isCat(a: any): a is Cat {
return a.name === 'kitty';
}
var x: Cat|{};
if(isCat(x)) {
x.meow(); // OK, x is Cat in this block
}
Typescript 能够在上面的 if 块中找出 x 的类型。
但是,如果我将代码更改为:
var x; // No type here. It's an "any" for now.
if(isCat(x)) {
x.meow(); // What!? It's type `any`??
}
Typescript 假定 x 是 any,即使在类型保护 if 语句的“安全”范围内。
【问题讨论】:
标签: types typescript