[英]Typescript array semantic error TS2532: Object is possibly 'undefined'
// 我在這個項目中使用 Typescript 4.4.4 和 node.js 12 LTS,Matrix 類在使用匯總編譯期間給我一個問題,我不知道為什么,我覺得一切正常
錯誤:/src/Matrix.ts(29,9):語義錯誤 TS2532:對象可能是“未定義”。
源代碼:
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;
似乎擺脫了右側的紅色下划線,但它在左側不起作用
使用!
i'm sure, typescript, you don't need to check undefined
m.data[i]![j]! = this.data[i]![j]!;
由於noUncheckedIndexedAccess
tsconfig
設置,您收到此警告: https : tsconfig
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.