type Foo = {
foo: number
items: Foo[]
}
type Bar = {
bar: number
items: Foo[]
}
function func(list: Bar[], indices: number[]) {
let cur: Foo[] | Bar[] = list
for (const index of indices) {
const item = cur[index] // error here
cur = item.items
}
}
为什么这是发生? cur
具有明确定义的类型。
index
也是如此。似乎流分析确定
cur
实际上是
Bar[]
,当我分配其他任何内容时出错了吗?
问题与流量分析不是。它在于一个事实,即当
cur
与Foo[]
.的结构不同时,正在类型
Bar[]
和
Bar
之间切换。如果您使
Foo
与
Bar
相同,则错误消失了。
Foo