[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")
`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", () => { })
标签:Functions,Typescript,const,Perform,value,getElementById,null,root,document 来源: https://www.cnblogs.com/Answer1215/p/14725206.html