'Item'隐式具有“任何类型”,因为它没有类型的注释,并在其自身的初始器中直接或间接引用

问题描述 投票:0回答:1
该代码在标题中失败,标题中的错误:

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[]
,当我分配其他任何内容时出错了吗?

typescript
1个回答
0
投票

问题与流量分析不是。它在于一个事实,即当

cur
Foo[]
.
的结构不同时,正在类型
Bar[]
Bar
之间切换。
如果您使

Foo

Bar
相同,则错误消失了。

Foo

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.