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