Skip to main content

提示 Object is possibly null

typescript 提示 Object is possibly "null",是因为可能不存在选择元素的情况。

加 null 的判断

方法一

const table = document.querySelector(".main-table");
if (table) {
table.setAttribute("height", "300px");
}

方法二

document.querySelector(".main-table")?.setAttribute("height", "300px");

方法三

const table = document.querySelector(".main-table");
table && table.setAttribute("height", "300px");

断言

使用断言方式,当然这是你能保证元素必定存在的情况

(document.querySelector('.main-table') as Element).setAttribute('height', '300px');