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

Matthew James Davis picture Matthew James Davis · Aug 20, 2015 · Viewed 8.7k times · Source

I have upgraded to Visual Studio 2015 Community with Typescript 1.5 Beta. I am getting the following error.

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

This is happening on the following line

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

I have set TypeScript tools version to both 1.4 and 1.5 and get the same error.

Answer

Fenton picture Fenton · Aug 20, 2015

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