Search code examples
typescripttype-assertiontypescript-typestypescript-lib-dom

How to assert a type of an HTMLElement in TypeScript?


I'm trying to do this:

var script:HTMLScriptElement = document.getElementsByName("script")[0];
alert(script.type);

but it's giving me an error:

Cannot convert 'Node' to 'HTMLScriptElement': Type 'Node' is missing property 'defer' from type 'HTMLScriptElement'
(elementName: string) => NodeList

I can't access the 'type' member of the script element unless I cast it to the correct type, but I don't know how to do this. I searched the docs & samples, but I couldn't find anything.


Solution

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