TypeScript: casting HTMLElement

后端 未结 13 2289
我寻月下人不归
我寻月下人不归 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:41

    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.

提交回复
热议问题