TypeScript: DOM types

By Xah Lee. Date: . Last updated: .

Check for null when using get element methods

whenever you use getElementById() or other get element methods, you should check for null. Otherwise it has the type of HTMLElement | null.

also, if it is input element, force it to HTMLInputElement. because by default it is HTMLElement, which doesn't have property .value

/*
whenever using get element method, always check for null.
also, if it is input element, force it to HTMLInputElement.
because by default it is HTMLElement, which doesn't have property .value
*/

const sliderSpread = document.getElementById("sliderSpread") as HTMLInputElement | null;

// check for null at runtime
if (!sliderSpread) throw new Error("#sliderSpread missing");

const spread = sliderSpread.value.toString() + "px";

Svg element types

type of svg elements, such as circle, is SVGElement

type of svg container, such as svg, is SVGSVGElement