Skip to content

'Canvas#getContext' almost never returns 'null' #19229

Open

Description

TypeScript Version: 2.5.3

Code:

let canvas: HTMLCanvasElement = document.createElement("canvas");
let ctx: CanvasRenderingContext2D = canvas.getContext("2d");
ctx.fillRect(0, 0, canvas.width, canvas.height);

Expected behavior:
No errors should occur because the type of canvas is HTMLCanvasElement.

Actual behavior:

test.ts(2,5): error TS2322: Type 'CanvasRenderingContext2D | null' is not assignable to type 'CanvasRenderingContext2D'.
  Type 'null' is not assignable to type 'CanvasRenderingContext2D'.

If I change the type of ctx to CanvasRenderingContext2D | null, then I get

test.ts(3,1): error TS2531: Object is possibly 'null'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureDomain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions