【发布时间】: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