Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 611
Matthew James Davis Avatar asked Aug 20 '15 10:08

Matthew James Davis


1 Answers

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

like image 143
Fenton Avatar answered Nov 15 '22 12:11

Fenton