microsoft / microsoft/TypeScript

HTMLCanvasElement.getContext() wrong typings when used with attributes.

Open
#16,860 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: lib.d.ts
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 2.4.1
Code

declare const canvas: HTMLCanvasElement;

//correct typing
const gl1 = canvas.getContext('webgl', { preserveDrawingBuffer: true, depth: false });

// wrong typing for gl2
const attributes = { preserveDrawingBuffer: true, depth: false };
const gl2 = canvas.getContext('webgl', attributes);

// If we copy HTMLCanvasElement.getContext() signatures it works
function getContext2(contextId: '2d', contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null;
function getContext2(contextId: 'webgl' | 'experimental-webgl', contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null;
function getContext2(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null { 
    return null;
 }


// correct typing
const gl3 = getContext2('webgl', attributes);

You can copy/paste that code on the playground to see it live (couldn't share: 'Text buffer too large to share').

Expected behavior:

Typing of all gl var should be WebGLRenderingContext.

Actual behavior:

Typing for gl2 is Canvas2DContextAttributes | WebGLRenderingContext.
I wanted to try to resolve this by changing the typings but then I found out that if we copy the exact same signature it works as expected.
So the typing indeed seem correct, dunno what's going on.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the HTMLCanvasElement.getContext() overloads and reproduce the issue in the TypeScript Playground using the code in the report. Trace why an object variable produces a union while the inline attributes work, then verify that gl2 is inferred as WebGLRenderingContext without breaking the 2D overload.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.