119

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 rectangle on this canvas. Here's the code

var canvas = document.getElementById("mycanvas");
var ctx: CanvasRenderingContext2D = canvas.getContext("2d");
ctx.fillStyle = "#00FF00";
ctx.fillRect(0, 0, 100, 100);

Unfortunately VisualStudio complains that

the property 'getContext' does no exist on value of type 'HTMLElement'

It marks the second line as an error. I thought this would be merely a warning but the code does not compile. VisualStudio says that

there were build errors. Would you like to continue and run the last successful build ?

I didn't like this error at all. Why is there no dynamic method invocation ? After all the method getContext definitely exists on my canvas element. However I thought this problem would be easy to solve. I just added a type annotiation for canvas:

var canvas : HTMLCanvasElement = document.getElementById("mycanvas");
var ctx: CanvasRenderingContext2D = canvas.getContext("2d");
ctx.fillStyle = "#00FF00";
ctx.fillRect(0, 0, 100, 100);

But the type system still wasn't satisfied. Here's the new error message, this time in the first line:

Cannot convert 'HTMLElement' to 'HTMLCanvasElement': Type 'HTMLElement' is missing property 'toDataURL' from type 'HTMLCanvasElement'

Well, I'm all out for static typing but this makes the language unusable. What does the type system want me to do ?

UPDATE:

Typescript has indeed no support for dynamic invocation and my problem can be solved with typecasts. My question is basically a duplicate of this one TypeScript: casting HTMLElement

8 Answers 8

258
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.

2
  • 14
    It is worth mentioning that it's better to use CanvasRenderingContext2D instead of any type for canvas context. Oct 3, 2014 at 11:22
  • 4
    Since TypeScript 1.8, it will recognize the constant string argument "2d", and .getContext("2d") will return with the type CanvasRenderingContext2D. You don't need to cast it explicitly. Jun 13, 2016 at 5:55
21
const canvas =  document.getElementById('stage') as HTMLCanvasElement;
4
  • 10
    Please explain why this code helps solve OP's problem rather than just a code answer. What does your code do differently, how does it help?
    – user5283119
    Feb 13, 2019 at 0:27
  • 1
    You copy/paste and it works. What's to explain here? If it doesn't work for you, then you should explain your problem and ask more specifically.
    – lenooh
    May 12, 2020 at 8:48
  • @lenooh "You copy/paste and it works" but OP does not learn anything. It would be more helpful if you could explain why your answer works. Nov 8, 2022 at 9:12
  • Lee Goddard: True. I hope the op got his answer. But for others who encounter this problem and we want to solve it without wasting time, this is perfect.
    – lenooh
    Nov 9, 2022 at 12:44
14

While other answers promote type assertions (that's what they are — TypeScript doesn't have type casts that actually change the type; they are merely a way of suppressing type checking errors), the intellectually honest way to approach your problem is to listen to the error messages.

In your case, there are 3 things that can go wrong:

  • document.getElementById("mycanvas") might return null, because no node of that id is found (it might have been renamed, not injected to the document yet, someone might have tried running your function in an environment without access to DOM)
  • document.getElementById("mycanvas") might return a reference to a DOM element, but this DOM element is not a HTMLCanvasElement
  • document.getElementById("mycanvas") did return a valid HTMLElement, it is indeed an HTMLCanvasElement, but the CanvasRenderingContext2D is not supported by the browser.

Instead of telling the compiler to shut up (and possibly finding yourself in a situation where a useless error message like Cannot read property 'getContext' of null is thrown), I recommend taking control over your application boundaries.

Make sure the element contains a HTMLCanvasElement

const getCanvasElementById = (id: string): HTMLCanvasElement => {
    const canvas = document.getElementById(id);

    if (!(canvas instanceof HTMLCanvasElement)) {
        throw new Error(`The element of id "${id}" is not a HTMLCanvasElement. Make sure a <canvas id="${id}""> element is present in the document.`);
    }

    return canvas;
}

Make sure the rendering context is supported by the browser

const getCanvasRenderingContext2D = (canvas: HTMLCanvasElement): CanvasRenderingContext2D => {
    const context = canvas.getContext('2d');

    if (context === null) {
        throw new Error('This browser does not support 2-dimensional canvas rendering contexts.');
    }

    return context;
}

Usage:

const ctx: CanvasRenderingContext2D = getCanvasRenderingContext2D(getCanvasElementById('mycanvas'))

ctx.fillStyle = "#00FF00";
ctx.fillRect(0, 0, 100, 100);

See TypeScript Playground.

2

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.

1

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.

1

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

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

I'd recommend

let canvas = document.getElementById('canvas') as
             HTMLCanvasElement;
1
  • Please include a more detailed explanation. This would work but why is it better or worse than other answers included here?
    – Kanembel
    Dec 12, 2022 at 20:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.