Accepted answer

I would try:

const canvas = <HTMLCanvasElement> document.getElementById('myChart');
const ctx = canvas.getContext('2d');

the purpose of Typescript is to avoid wrong types. By default document.getElementById returns a HTMLElementtype which is a generic type. In order to make your app understand it is a canvas element you need to cast it using <CastedToType> syntax.


simply cast canvas as HTMLCanvasElement inline as follows

const canvas = document.getElementById('myChart');
const ctx = (canvas as HTMLCanvasElement).getContext('2d');



const canvas = document.getElementsByTagName('canvas')[0]; will return an HTMLCanvasElement, but

const canvas = document.getElementById('someId'); will return an HTMLElement object instead of HTMLCanvasElement, which has no 'getContext' method.


Best to use runtime type validation which TS understands.

const canvas = document.querySelector('#my-canvas')
if (!(canvas instanceof HTMLCanvasElement)) return


This handles the case where the element you query for has the wrong tag name.

<div id="my-canvas" /> 
<canvas id="my-canvas1" />


Try this:

const canvas = document.getElementById('myChart') as HTMLCanvasElement;
const ctx = canvas.getContext('2d');

Related Query

More Query from same tag