Fails to perform type narrowing on functions that return "never"
See original GitHub issueBug Report
🔎 Search Terms
type narrowing never
🕗 Version & Regression Information
- v4.5.2
- v4.4.4
- v4.3.5
- v4.2.3
- v4.1.5
- v4.0.5
- v3.9,7
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about this.
⏯ Playground Link
Playground link with relevant code
💻 Code
type ShouldNeverReturnFunction = () => never;
let shouldNeverReturn: ShouldNeverReturnFunction | null = null;
function foo(): never {
if (shouldNeverReturn === null) {
throw new Error('The "shouldNeverReturn" function was not initialized.');
}
shouldNeverReturn();
}
🙁 Actual behavior
The TypeScript compiler refuses to compile this code.
🙂 Expected behavior
I expect the TypeScript compiler to compile this code.
The error message says that the foo
function has “a reachable end point”, but that is clearly false, so the TypeScript compiler seems to be drunk. 🍺🥴
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:6 (4 by maintainers)
Top Results From Across the Web
Documentation - Narrowing - TypeScript
If we'd assigned a boolean to x , we'd have seen an error since that wasn't part of the declared type. x =...
Read more >Typescript narrowing doesn't work when function is always ...
a) { f() } return s. x. a // ERROR: can be undefined! } I thought returning never will help the compiler to...
Read more >Narrowing Types in TypeScript - Formidable Labs
Type narrowing is just what it sounds like—narrowing down a general type into something more precise. If you've ever dealt with union types, ......
Read more >Common issues and solutions - mypy 0.991 documentation
The function containing the error is not annotated. Functions that do not have any annotations (neither for any argument nor for the return...
Read more >Master Type Narrowing In Typescript - Nicos Tsourektsidis
function getWidth(width?: string | number): string { if (typeof width === 'number') { return `${width}px`; } return width; // Error: Type ...
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
I think it’s in principle possible to expand the checking to cover unions, but this seems like a fairly rare case. The old workaround of
return shouldNeverReturn();
works well here. We can look into it more if it’s commonly encountered#32695 mentions:
shouldNeverReturn
does not resolve to such a function, it only is later on narrowed to one. Unfortunately the PR does not mention unions, so it’s not clear whether this is intentional (my guess) or not.