6
我在循环内的三元运算符中使用TypeScript类型的警卫,并看到我不明白的行为。TypeScript类型的警卫Oddity
我的接口
interface INamed {
name: string;
}
interface IOtherNamed extends INamed {
otherName: string;
}
我型后卫
function isOther(obj: any): obj is IOtherNamed {
... // some check that returns boolean
}
一般使用Sample
var list: Array<{named: INamed}> = [];
for(let item of list) {
var other: IOtherNamed = ...
}
在我的循环内部,我正在使用我的类型守护程序将我当前的项目或null分配给IOtherNamed的变量。
这不起作用
// Compiler Error: INamed is not assignable to IOtherNamed
for(let item of list) {
var other: IOtherNamed = isOther(item.named) ? item.named : null;
}
这确实
for(let item of list) {
var named: INamed = item.named;
var other2: IOtherNamed = isOther(named) ? named : null;
}
我的问题
- 这是由设计,这些作品的一个Wh是ile另一个不?
- 如果按照设计,这里的细微差别决定了它的工作与否?特别是为什么分配我的对象到一个新的变量(没有任何类型的变化)摆脱编译器错误?
非常感谢,我需要的信息。 – bingles
并将在TS 2.0中修复:https://github.com/Microsoft/TypeScript/issues/3812 – Alex