简体   繁体   English

打字稿数组语义错误 TS2532:对象可能是“未定义”

[英]Typescript array semantic error TS2532: Object is possibly 'undefined'

// I'm using Typescript 4.4.4 and node.js 12 LTS for this project, the Matrix class is giving me a problem during compilation with rollup, I'm not sure why, everything looks ok to me // 我在这个项目中使用 Typescript 4.4.4 和 node.js 12 LTS,Matrix 类在使用汇总编译期间给我一个问题,我不知道为什么,我觉得一切正常

Error:/src/Matrix.ts(29,9): semantic error TS2532: Object is possibly 'undefined'.错误:/src/Matrix.ts(29,9):语义错误 TS2532:对象可能是“未定义”。

The source code:源代码:

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;
  }
...
}

this is the line with the error:这是错误所在的行:

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

and:和:

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

seemed to get rid of the red underline on the right side, but it doesn't work on he left side似乎摆脱了右侧的红色下划线,但它在左侧不起作用

use !使用! for i'm sure, typescript, you don't need to check undefined i'm sure, typescript, you don't need to check undefined

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

you've got this warning because of the noUncheckedIndexedAccess tsconfig setting: https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess由于noUncheckedIndexedAccess tsconfig设置,您收到此警告: https : tsconfig

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeScript 错误 TS2532:Object 可能是“未定义”? - TypeScript Error TS2532: Object is possibly 'undefined'? TypeScript 2:Import语句生成TS2532:“对象可能是&#39;undefined&#39;。” - TypeScript 2: Import statement generates TS2532: “Object is possibly 'undefined'.” TS2532:对象可能是“未定义”。 在 array.map() 上 - TS2532: Object is possibly 'undefined'. on array.map() 对象可能是“未定义” ts2532 - object is possibly "undefined" ts2532 错误 TS2532:对象可能是“未定义” - 使用“?” 操作员 - error TS2532: Object is possibly 'undefined' - Using "?." operator Ts2532、Object 可能是“未定义” - Ts2532, Object is possibly 'undefined' 类型保护错误TS2532后,可能未定义Typescript对象 - Typescript Object is possibly undefined after type guard error TS2532 Typescript 显示“this”错误 Object 说 TS2532: Object 在 vue 方法中可能是“未定义” - Typescript displays error for "this" Object saying TS2532: Object is possibly 'undefined' inside of vue methods 在另一个函数中使用时,变量可能未定义(打字稿“错误TS2532”) - Variable possibly undefined when used inside another function (Typescript “error TS2532) 打字稿-内联未定义检查不起作用(对象可能是&#39;undefined&#39;.ts(2532)) - Typescript - Inline undefined check not working (Object is possibly 'undefined'.ts(2532))
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM