snippettypescriptCriticalCanonical
How to assert a type of an HTMLElement in TypeScript?
Viewed 0 times
typescripthowasserthtmlelementtype
Problem
I'm trying to do this:
but it's giving me an error:
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.
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) => NodeListI 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:
However, unfortunately you cannot do:
You get the error
But you can do :
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.