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 HTMLElement
type 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.
Source:stackexchange.com