Does anyone know how to cast in TypeScript?
I\'m trying to do this:
var script:HTMLScriptElement = document.getElementsByName(\"script\")[0];
alert(s
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.