How To Use document.getElementById() in TypeScript

To be able to use document.getElementById() in TypeScript we have to perform type assertion and check the return value is not null before we can operate on them. This article will provide detailed instructions with examples. Let’s begin

Ways to be able to use document.getElementById() in TypeScript

In TypeScript, this method will return the data type of HTMLElement, so to be able to operate on the correct data type that we want, we must use type assertion and must use additional null type in a union because if there is no element to get on DOM, this method will return null data type.

Using type assertion

When using this method to perform data retrieval on the DOM, we should always add the type assertion using the "as" keyword to tell TypeScript the correct data type.

Example:

const canvas = document.getElementById("my-canvas") as HTMLCanvasElement | null

In the above example, we want to get the my-canvas element to be able to do the work. We must immediately add as “HTMLCanvasElement | null" to let TypeScript understand that we are going to operate on a canvas element, and at the same time, we add a null data type because if this element is not present on the DOM, the return data type will be null.

Null type check

Because the return data type can be null, we must check before we call methods on this object to avoid the error.

Example:

const canvas = document.getElementById("my-canvas") as HTMLCanvasElement | null;

// Check data types before call methods
const check = canvas !== null && "Canvas not null";
console.log(check);

Output:

Canvas not null

In the above example, we use a conditional expression. We check if the canvas variable is not null, then we will assign data to the check variable and then print it to the screen.

You can also use optional chaining to check for null in a very succinct way

Example:

const canvas = document.getElementById("my-canvas") as HTMLCanvasElement | null;

// Using optional chaining "?" to check if not null
const check = canvas?.getContext("2d");
console.log(check);

Output:

CanvasRenderingContext2D {canvas: canvas#my-canvas, globalAlpha: 1, globalCompositeOperation: 'source-over', filter: 'none', imageSmoothingEnabled: true, …}

In the above example, if the canvas variable is not null, then we can call the getContext() method. Without this constraint, the program will error.

Summary

In short, to be able to use document.getElementById() in TypeScript, we have to do type assertion and check if the return value is not null before we can perform the action we want. We have to do all the above steps because TypeScript is very strict in type checking.

Leave a Reply

Your email address will not be published. Required fields are marked *