Search code examples
reactjstypescriptcanvas

Property 'clearRect' does not exist on type 'HTMLCanvasElement'


canvas has type HTMLCanvasElement | null

when i call clearRect method in canvas then i get this error:

Property 'clearRect' does not exist on type 'HTMLCanvasElement'.

this.canvas?.clearRect()

I dont know how solve this problem. Please help me.


Solution

  • Because it doesn't exists on HTMLCanvasElement.

    It exists on CanvasRenderingContext2D

    if (this.canvas) {
      const ctx = this.canvas.getContext('2d');
      ctx.clearRect();
    }