删除| null Typescript type
问题描述:
我刚开始学习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));
答
如果实际上做一些事情在if
块,使myCanvas
非null
,打字稿会认识到:
let myCanvas = document.getElementById('point_fiel');
if (myCanvas == null) {
return; // or throw, etc.
}
useHTMLElement(myCanvas); // OK
或
let myCanvas = document.getElementById('point_fiel');
if (myCanvas == null) {
myCanvas = document.createElement('canvas');
}
useHTMLElement(myCanvas); // OK
答
打字稿typeguards也认识到instanceof操作符 - 非空时有用并不是你所需要知道的
let myCanvas = document.getElementById('point_fiel');
if (myCanvas instanceof HTMLCanvasElement) {
usHTMLElement(myCanvas);
} else if (myCanvas instanceof HTMLElement) {
// was expecting a Canvas but got something else
// take appropriate action
} else {
// no element found
}
完美,谢谢! – Ben