我刚开始学习TypeScript,有些情况下我会得到一个可能是类型或null的错误。有没有一种优雅的处理这些情况的方式?
function useHTMLElement(item: HTMLElement) {
console.log("it worked!")
}
let myCanvas = document.getElementById('point_file');
if (myCanvas == null) {
// abort or do something to make it non-null
}
// now I know myCanvas is not null. But the type is still `HTMLElement | null`
// I want to pass it to functions that only accept HTMLElement.
// is there a good way to tell TypeScript that it's not null anymore?
useHTMLElement(myCanvas);
我写了下面这个函数,它似乎可以工作,但这似乎是一个常见的情况,我想知道语言本身是否提供了类似的功能。
function ensureNonNull <T> (item: T | null) : T {
if (item == null) {
throw new Error("It's dead Jim!")
}
// cast it
return <T> item;
}
useHTMLElement(ensureNonNull(myCanvas));