microsoft / microsoft/TypeScript
HTMLCanvasElement.getContext() wrong typings when used with attributes.
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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