Remove | null from Typescript type
If you actually do something in the if
block to make myCanvas
non-null
, TypeScript will recognize that:
let myCanvas = document.getElementById('point_fiel');
if (myCanvas == null) {
return; // or throw, etc.
}
useHTMLElement(myCanvas); // OK
or
let myCanvas = document.getElementById('point_fiel');
if (myCanvas == null) {
myCanvas = document.createElement('canvas');
}
useHTMLElement(myCanvas); // OK
Typescript typeguards also recognise the instanceof operator - useful when not-null isn't all you need to know
let myCanvas = document.getElementById('point_fiel');
if (myCanvas instanceof HTMLCanvasElement) {
useHTMLElement(myCanvas);
} else if (myCanvas instanceof HTMLElement) {
// was expecting a Canvas but got something else
// take appropriate action
} else {
// no element found
}