TypeScript: casting HTMLElement

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

    I would also recommend the sitepen guides

    https://www.sitepen.com/blog/2013/12/31/definitive-guide-to-typescript/ (see below) and https://www.sitepen.com/blog/2014/08/22/advanced-typescript-concepts-classes-types/

    TypeScript also allows you to specify different return types when an exact string is provided as an argument to a function. For example, TypeScript’s ambient declaration for the DOM’s createElement method looks like this:

    createElement(tagName: 'a'): HTMLAnchorElement;
    createElement(tagName: 'abbr'): HTMLElement;
    createElement(tagName: 'address'): HTMLElement;
    createElement(tagName: 'area'): HTMLAreaElement;
    // ... etc.
    createElement(tagName: string): HTMLElement;
    

    This means, in TypeScript, when you call e.g. document.createElement('video'), TypeScript knows the return value is an HTMLVideoElement and will be able to ensure you are interacting correctly with the DOM Video API without any need to type assert.

提交回复
热议问题