【问题标题】:Odd error thrown by typescript compiler when looping over union typed array循环遍历联合类型数组时打字稿编译器抛出的奇怪错误
【发布时间】: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


    【解决方案1】:

    如果您为 newIns[i][j] 元素创建常量,这将起作用。对她来说,TS 就能正确处理类型。

    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){
          const element = newIns[i][j]
            if(element !== 0){
                element.x = 30
            }
        }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多