1
我刚开始学习TypeScript,在某些情况下,我得到的可能是Type或null。有没有一种优雅的方式来处理这些案件?删除| null Typescript type
function useHTMLElement(item: HTMLElement) {
console.log("it worked!")
}
let myCanvas = document.getElementById('point_fiel');
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));
完美,谢谢! – Ben