Categories
TypeScript Answers

How to assert a type of an HTMLElement in TypeScript?

Spread the love

Sometimes, we want to assert a type of an HTMLElement in TypeScript.

In this article, we’ll look at how to assert a type of an HTMLElement in TypeScript.

How to assert a type of an HTMLElement in TypeScript?

To assert a type of an HTMLElement in TypeScript, we can use brackets or use the as keyword.

For instance, we write

const script: HTMLScriptElement = <HTMLScriptElement>(
  document.getElementsByTagName("script")[0]
);

to cast document.getElementsByTagName("script")[0] to type HTMLScriptElement.

We can also write

const script: HTMLScriptElement = document.getElementsByTagName(
  "script"
)[0] as HTMLScriptElement;

to use as to cast document.getElementsByTagName("script")[0] to type HTMLScriptElement.

Conclusion

To assert a type of an HTMLElement in TypeScript, we can use brackets or use the as keyword.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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