[Typescript] Perform null Checks with Assertion Functions

In this lesson, we're going to look at how to perform null checks with assertion functions. We're going to assert that a nullable value doesn't hold the value null. In the process, we're going to learn how assertion functions integrate with TypeScript's control flow analysis.

const root = document.getElementById("root")

[Typescript] Perform null Checks with Assertion Functions

`root` can be `HTMLElement` or `null` type.

root.addEventListener("click", () => {
    
})

It reports `root` is possible to be null

[Typescript] Perform null Checks with Assertion Functions

 

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", () => {

})

 

上一篇:中国亚硫酸钙市场趋势报告、技术动态创新及市场预测


下一篇:年度盘点|2021 年阿里云可观测实践回顾