TypeScript: problems with type system

前端 未结 7 2405

I\'m just testing typescript in VisualStudio 2012 and have a problem with its type system. My html site has a canvas tag with the id \"mycanvas\". I\'m trying to draw a rect

7条回答
  •  伪装坚强ぢ
    2020-12-12 23:58

    I had the same problem, but with SVGSVGElement instead of HTMLCanvasElement. Casting to SVGSVGElement gave a compile-time error:

    var mySvg = document.getElementById('mySvg');
    

    Cannot convert 'HTMLElement' to 'SVGSVGElement':
    Type 'HTMLElement' is missing property 'width' from type 'SVGSVGElement'.
    Type 'SVGSVGElement' is missing property 'onmouseleave' from type 'HTMLElement'.

    If fixed it by first casting to 'any':

    var mySvg = document.getElementById('mySvg');
    

    or this way (it has the identical effect)

    var mySvg: SVGSVGElement = document.getElementById('mySvg');
    

    Now mySvg is strongly typed as SVGSVGElement.

提交回复
热议问题