Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React TypeScript: Type 'null' is not assignable to type 'CanvasRenderingContext2D'

I seem to be able to create the canvas but when I come to get the context

  const resizeImage = async (maxSize: number) => {
    const image = originalImage;
    const id = positionId;
    const resizeCanvas = document.createElement('canvas');
    resizeCanvas.width = maxSize;
    resizeCanvas.height = maxSize;
    const ctx: CanvasRenderingContext2D = resizeCanvas.getContext('2D');
//         ^ Error
    ...

The error is

Type 'CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext | null' is not assignable to type 'CanvasRenderingContext2D'.
  Type 'null' is not assignable to type 'CanvasRenderingContext2D'.ts(2322)
like image 879
Bill Avatar asked May 20 '26 03:05

Bill


2 Answers

The error means that resizeCanvas.getContext('2D') can return null, but you are assigning it to a variable of type CanvasRenderingContext2D (i.e. this cannot be null). So you need to make sure the result is not null before assigning it. Also I guess you want to make sure it's of type CanvasRenderingContext2D rather than ImageBitmapRenderingContext etc. You could do:

 const resizeImage = async (maxSize: number) => {
    const image = originalImage;
    const id = positionId;
    const resizeCanvas = document.createElement('canvas');
    resizeCanvas.width = maxSize;
    resizeCanvas.height = maxSize;
    const res = resizeCanvas.getContext('2D');
    if (!res || !(res instanceof CanvasRenderingContext2D)) {
        throw new Error('Failed to get 2D context');
    }
    const ctx: CanvasRenderingContext2D = res;
like image 144
Collierre Avatar answered May 22 '26 23:05

Collierre


Just declare yout variable like this type: CanvasRenderingContext2D | null;


export class AppComponent implements OnInit{
  @ViewChild('soccerField', { static: true }) soccerCanvas: ElementRef<HTMLCanvasElement> ;
  private ctx: CanvasRenderingContext2D | null;

  ngOnInit(): void {
    let element = this.soccerCanvas.nativeElement ;
    this.ctx = element.getContext('2d');
  }
like image 24
Mauricio Gracia Gutierrez Avatar answered May 22 '26 23:05

Mauricio Gracia Gutierrez