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
You may have to add DOM
to compilerOptions.lib
in your tsconfig.json
.
// 'tsconfig.json'
{
"compilerOptions": {
"target": "ES2017",
"module": "commonjs",
"lib": [
"es5",
"DOM",
"esnext"
]
}
}
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.
const canvas = document.getElementById('stage') as HTMLCanvasElement;
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.
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.
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"
}