'Canvas#getContext' almost never returns 'null'
See original GitHub issueTypeScript 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'.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:2
- Comments:8 (4 by maintainers)
Top Results From Across the Web
canvas getContext("2d") returns null - Stack Overflow
If the contextType doesn't match a possible drawing context, or differs from the first contextType requested, null is returned. Share.
Read more >Activity | Android Developers
An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class...
Read more >Editor's Canvas getContext("2d") returns null - Help & Support
I'm writing a custom script using Editor API. Noticed that Editor's Canvas getContext(“2d”) returns null. Is there any other way to get the ......
Read more >WebGL Specification - Khronos Registry
If drawing buffer creation failed, perform the following steps: Fire a WebGL context creation error at canvas. Return null and terminate these ...
Read more >Component.AccessibleAWTComponent (Java SE 18 & JDK 18)
Gets the accessible name of this object. This should almost never return java.awt.Component.getName() , as that generally isn't a localized name, and doesn't ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This just seems like a perfect use case for
!
, I don’t think changing the dts is necessary:For reference,
Is a decent way to use it in a typesafe way without really getting in the way; but if you must remove
null
from the type definition, you should probably only remove it from the overloads for"2d"
and"webgl"
(and I guess there should be one for"bitmaprenderer"
), but not the base signature withstring
.