[英]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.