Type 'CanvasRenderingContext2D | WebGLRenderingContext' is not assignable to type 'CanvasRenderingContext2D' Type 'CanvasRenderingContext2D | WebGLRenderingContext' is not assignable to type 'CanvasRenderingContext2D' typescript typescript

Type 'CanvasRenderingContext2D | WebGLRenderingContext' is not assignable to type 'CanvasRenderingContext2D'


From the error message, the return type of getContext appears to be a union type, which means it is either one of CanvasRenderingContext2D or WebGLRenderingContext.

The compiler cannot tell which, so you need to help it out:

var ctx = <CanvasRenderingContext2D> canvas.getContext("2d");

However, if I try this with the latest version of everything, this works just fine:

var canvas = <HTMLCanvasElement> $('#example').find('canvas').get(0);var ctx: CanvasRenderingContext2D = canvas.getContext("2d");

So it looks like something isn't quite right.

The current definition of getContext has a specialized signature for the value "2d" that should give you back a CanvasRenderingContext2D. Here are the three signatures...

  1. "2d" : CanvasRenderingContext2D
  2. "experimental-webgl" : WebGLRenderingContext
  3. other string : CanvasRenderingContext2D | WebGLRenderingContext

It should only give you back the union type if it doesn't recognise the string being passed in.

If your auto-completion doesn't suggest these three overloads when you type the ( after getContext, that may indicate a problem.

Auto-Completion for getContext with 2d argument