HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCriticalCanonical

How to assert a type of an HTMLElement in TypeScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescripthowasserthtmlelementtype

Problem

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 = document.getElementsByName("script")[0];


However, unfortunately you cannot do:

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


You get the error

Cannot convert 'NodeList' to 'HTMLScriptElement[]'


But you can do :

(document.getElementsByName(id))[0];

Code Snippets

var script = <HTMLScriptElement>document.getElementsByName("script")[0];
var script = (<HTMLScriptElement[]>document.getElementsByName(id))[0];
Cannot convert 'NodeList' to 'HTMLScriptElement[]'
(<HTMLScriptElement[]><any>document.getElementsByName(id))[0];

Context

Stack Overflow Q#12686927, score: 285

Revisions (0)

No revisions yet.