【发布时间】:2023-01-28 22:21:47
【问题描述】:
这是一个例子(不是一个好例子:p):
type RandomType = {x: number, y: number}
type UnifiedTypes = RandomType | 0
type ArrayOfTypes = Array<(RandomType | UnifiedTypes)[]>
const newIns: ArrayOfTypes = [[0, {x: 10, y: 201}], [0, {x: 10, y: 201}]]
for(let i=0; i < newIns.length; ++i){
for(let j=0; j < newIns[i].length; ++j){
if(newIns[i][j] !== 0){
newIns[i][j].x = 30 // Property 'x' does not exist on type 'UnifiedTypes'. Property 'x' does not exist on type '0'
}
}
}
// Hoewever, when outside of loop compiler runs fine
if(newIns[0][0] !== 0) {
newIns[0][0].x = 33; // no error thrown
}
循环遍历联合类型数组时,缩小范围似乎不起作用,所以我有点迷路了。我错过了smt吗?
通过缩小索引元素将保存的类型,打字稿编译器应该能够找出指定索引中元素数组的类型,因此赋值是安全的。
【问题讨论】:
标签: typescript