【问题标题】:Typescript array semantic error TS2532: Object is possibly 'undefined'打字稿数组语义错误 TS2532:对象可能是“未定义”
【发布时间】:2021-12-21 20:53:59
【问题描述】:

// 我在这个项目中使用 Typescript 4.4.4 和 node.js 12 LTS,Matrix 类在使用汇总编译期间给我一个问题,我不知道为什么,对我来说一切正常

Error:/src/Matrix.ts(29,9): 语义错误 TS2532: Object is possible '未定义'。

源代码:

export class Matrix {
  rows: number;
  cols: number;
  data: number[][];
  constructor(rows: number, cols: number) {
    this.rows = rows;
    this.cols = cols;
    this.data = Array(this.rows)
      .fill(1)
      .map(() => Array(this.cols).fill(0));
  }

  copy() {
    const m = new Matrix(this.rows, this.cols);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.cols; j++) {
        m.data[i][j] = this.data[i][j];
      }
    }
    return m;
  }
...
}

这是有错误的那一行:

  m.data[i][j] = this.data[i][j];

和:

 m.data[i][j] = this?.data?.[i]?.[j] as number;

右侧的红色下划线好像去掉了,但是左侧不行

【问题讨论】:

    标签: javascript typescript undefined


    【解决方案1】:

    ! 用于i'm sure, typescript, you don't need to check undefined

     m.data[i]![j]! = this.data[i]![j]!;
    

    您收到此警告是因为 noUncheckedIndexedAccess tsconfig 设置:https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess

    【讨论】:

      猜你喜欢
      • 2018-09-11
      • 2022-01-05
      • 2021-10-07
      • 2021-12-29
      • 2022-01-20
      • 2020-12-01
      • 2021-11-29
      • 2019-07-30
      相关资源
      最近更新 更多