对象可能是 'null'.ts(2531),即使我在 if 条件下检查它也会发生错误
Object is possibly 'null'.ts(2531), Error occurs even though I am checking that in the if condition
if (document.getElementById(`${element.id}-element`)) {
document.getElementById(`${element.id}-element`).onmousedown = // *document.getElementById(`${element.id}-element`)* gives me object is possibly null error
dragMouseDown;
} else {
element.onmousedown = dragMouseDown;
}
所以我尝试了非空断言
if (document.getElementById(`${element.id}-element`)) {
document.getElementById(`${element.id}-element`)!.onmousedown =
dragMouseDown;
} else {
element.onmousedown = dragMouseDown;
}
但这给了我禁止的非空断言@typescript-eslint/no-non-null-assertion。有没有其他方法可以避免对象可能为空的错误?
提前致谢:)
不要重复表达式,而是将其存储到变量中。
const element2 = document.getElementById(`${element.id}-element`);
if (element2) {
element2.onmousedown = dragMouseDown;
} else {
element.onmousedown = dragMouseDown;
}
更好的是,使用无效合并并摆脱 if-else 块。
const element2 = document.getElementById(`${element.id}-element`) ?? element;
element2.onmousedown = dragMouseDown;
if (document.getElementById(`${element.id}-element`)) {
document.getElementById(`${element.id}-element`).onmousedown = // *document.getElementById(`${element.id}-element`)* gives me object is possibly null error
dragMouseDown;
} else {
element.onmousedown = dragMouseDown;
}
所以我尝试了非空断言
if (document.getElementById(`${element.id}-element`)) {
document.getElementById(`${element.id}-element`)!.onmousedown =
dragMouseDown;
} else {
element.onmousedown = dragMouseDown;
}
但这给了我禁止的非空断言@typescript-eslint/no-non-null-assertion。有没有其他方法可以避免对象可能为空的错误?
提前致谢:)
不要重复表达式,而是将其存储到变量中。
const element2 = document.getElementById(`${element.id}-element`);
if (element2) {
element2.onmousedown = dragMouseDown;
} else {
element.onmousedown = dragMouseDown;
}
更好的是,使用无效合并并摆脱 if-else 块。
const element2 = document.getElementById(`${element.id}-element`) ?? element;
element2.onmousedown = dragMouseDown;