[Chartjs]-Property 'getContext' does not exist on type 'HTMLElement'

93πŸ‘

βœ…

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.

29πŸ‘

Try this:

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

2πŸ‘

Best to use runtime type validation which TS understands.

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

canvas.getContext(...)

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

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

1πŸ‘

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.

1πŸ‘

simply cast canvas as HTMLCanvasElement inline as follows

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

cheers.

Leave a comment