TypeScript: problems with type system

前端 未结 7 2399

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:41

    You may have to add DOM to compilerOptions.lib in your tsconfig.json.

    // 'tsconfig.json'
     {
      "compilerOptions": {
        "target": "ES2017",
        "module": "commonjs",
        "lib": [
          "es5",
          "DOM",
          "esnext"
        ]
      }
    }
    
    0 讨论(0)
  • 2020-12-12 23:47
    var canvas = <HTMLCanvasElement> document.getElementById("mycanvas");
    var ctx = canvas.getContext("2d");
    

    or using dynamic lookup with the any type (no typechecking):

    var canvas : any = document.getElementById("mycanvas");
    var ctx = canvas.getContext("2d");
    

    You can look at the different types in lib.d.ts.

    0 讨论(0)
  • 2020-12-12 23:53
    const canvas =  document.getElementById('stage') as HTMLCanvasElement;
    
    0 讨论(0)
  • 2020-12-12 23:57

    It seems this is being corrected in the .9 version of TypeScript: http://blogs.msdn.com/b/typescript/archive/2013/03/25/working-on-typescript-0-9-generics-overload-on-constants-and-compiler-performance.aspx See the section on "Overload on Constants" where the canvas tag is explicitly shown.

    0 讨论(0)
  • 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 = <SVGSVGElement>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 = <SVGSVGElement><any>document.getElementById('mySvg');
    

    or this way (it has the identical effect)

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

    Now mySvg is strongly typed as SVGSVGElement.

    0 讨论(0)
  • 2020-12-12 23:58

    This is an old topic... maybe dead to 2012, but exciting and new to VS Code and typescript.

    I had to do the following to get this to work in VS Code with the following package references.

    const demoCanvas: HTMLCanvasElement = document.getElementById('rfrnCanvas') as any;
    
            if(demoCanvas.getContext) {
                const context = demoCanvas.getContext('2d');
    
                if(context) {
                    reactangle(context);
                }
            }
    

    Typescript Version:

    {
        "@typescript-eslint/eslint-plugin": "^2.29.0",
        "@typescript-eslint/parser": "^2.29.0",
        "typescript": "^3.7.5"
    }
    
    
    0 讨论(0)
提交回复
热议问题