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.