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