[Chartjs]-Type check for getElementById only works with optional chaining, not with type check

1👍

The problem isn’t with canv. The compiler knows that canv itself is not null, but if you look at the return type for canv.getContext("2d"), that is possibly null:

HTMLCanvasElement.getContext(
  contextId: "2d", 
  options?: CanvasRenderingContext2DSettings | undefined
): CanvasRenderingContext2D | null

That is what the "Object is possibly null" error is complaining about. You can fix that with optional chaining after that call, such as:

if (canv !== null && canv !== undefined) {
    const gradient = canv.getContext("2d")?.createLinearGradient(0, 0, 0, canv.height)
}

Or you can do a more spelled-out type check:

if (canv !== null && canv !== undefined) {
    const context = canv.getContext("2d");
    if (context) {
        const gradient = context.createLinearGradient(0, 0, 0, canv.height)
    }
}

Or anything else that convinces the compiler that canv.getContext("2d") will not be null:

if (canv !== null && canv !== undefined) {
    const gradient = (canv.getContext("2d") || { createLinearGradient: () => undefined })
        .createLinearGradient(0, 0, 0, canv.height);
}

Playground link to code

Leave a comment