How to assert a type of an HTMLElement in TypeScript?

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];

Leave a Comment