在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
In this lesson, we're going to look at how to perform const root = document.getElementById("root") `root` can be `HTMLElement` or `null` type. root.addEventListener("click", () => {
})
It reports `root` is possible to be null
It is possible to supress the error by using assert not null operator `!` const root = document.getElementById("root")!
But it is still possible has runtime error. We can use if check: const root = document.getElementById("root") if (root === null) { throw Error(`cannot find #root element`) } root.addEventListener("click", () => { })
Better, we can use assertion: function assertIsNonNullish<T>( value: T, message: string ): asserts value is NonNullable<T> { if (value === null || value === undefined) { throw Error(message); } } const root = document.getElementById("root") assertIsNonNullish(root, "Cannot find #root element") root.addEventListener("click", () => { })
|
请发表评论