Does anyone know how to cast in TypeScript?
I\'m trying to do this:
var script:HTMLScriptElement = document.getElementsByName(\"script\")[0];
alert(s
We could type our variable with an explicit return type:
const script: HTMLScriptElement = document.getElementsByName(id).item(0);
Or assert as (needed with TSX):
const script = document.getElementsByName(id).item(0) as HTMLScriptElement;
Or in simpler cases assert with angle-bracket syntax.
A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler.
Documentation:
TypeScript - Basic Types - Type assertions