Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert a type of an HTMLElement in TypeScript?

People also ask

How do I get HTMLElement?

To get HTMLElement from element with TypeScript, we can cast elements to HTMLElement . const nodes = document. querySelectorAll<HTMLElement>("a"); to cast the items in the node list returned by querySelectorAll to HTMLElement .

What is type element in TypeScript?

Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element.

What is HTMLInputElement?

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.


TypeScript uses '<>' to surround casts, so the above becomes:

var script = <HTMLScriptElement>document.getElementsByName("script")[0];

However, unfortunately you cannot do:

var script = (<HTMLScriptElement[]>document.getElementsByName(id))[0];

You get the error

Cannot convert 'NodeList' to 'HTMLScriptElement[]'

But you can do :

(<HTMLScriptElement[]><any>document.getElementsByName(id))[0];

As of TypeScript 0.9 the lib.d.ts file uses specialized overload signatures that return the correct types for calls to getElementsByTagName.

This means you no longer need to use type assertions to change the type:

// No type assertions needed
var script: HTMLScriptElement = document.getElementsByTagName('script')[0];
alert(script.type);

Do not type cast. Never. Use type guards:

const e = document.getElementsByName("script")[0];
if (!(e instanceof HTMLScriptElement)) 
  throw new Error(`Expected e to be an HTMLScriptElement, was ${e && e.constructor && e.constructor.name || e}`);
// locally TypeScript now types e as an HTMLScriptElement, same as if you casted it.

Let the compiler do the work for you and get errors when your assumptions turn out wrong.

It may look overkill in this case, but it will help you a lot if you come back later and change the selector, like adding a class that is missing in the dom, for example.


You always can hack type system using:

var script = (<HTMLScriptElement[]><any>document.getElementsByName(id))[0];