TypeScript: casting HTMLElement

后端 未结 13 2337
我寻月下人不归
我寻月下人不归 2020-12-02 05:34

Does anyone know how to cast in TypeScript?

I\'m trying to do this:

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


        
13条回答
  •  广开言路
    2020-12-02 05:38

    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

提交回复
热议问题