Type parameter constrained to union cannot be exhaustively narrowed to 'never'
See original GitHub issueTypeScript Version: 2.1.1 (http://www.typescriptlang.org/play/index.html)
Code
type Type = "a" | "b"
function isA(a: any): a is "a" {
return a === "a"
}
function isB(a: any): a is "b" {
return a === "b"
}
function assertNever(arg: never) {
throw new Error("This should never be called")
}
function handleAction<T extends Type>(type: T) {
if (isA(type)) {
return type
} else if (isB(type)) {
return type
} else {
assertNever(type)
}
}
Expected behavior: No compilation error
Actual behavior: Argument of type ‘T’ is not assignable to type ‘never’
Issue Analytics
- State:
- Created 7 years ago
- Reactions:3
- Comments:11 (2 by maintainers)
Top Results From Across the Web
Generic type extending union is not narrowed by type guard
In theory it would be sound to narrow T to something like "a type which extends string | number but whose intersection with...
Read more >A complete guide to TypeScript's never type - Zhenghao
Inadmissible parameters in generics and functions. Intersection of incompatible types. An empty union (a union type of nothingness). The return ...
Read more >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 >Widening and Narrowing in Typescript | manual - GitHub Pages
The types null and undefined are converted to any . This happens recursively in object types, union types, and array types (including tuples)....
Read more >Really Advanced Typescript Types - Tableau Engineering Blog
Usually. I don't know how many hours I've wasted in life reading Java code that throws when constructor parameters are null , never...
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 have a problem which I think is related to this.
TS should be smart enough to know I have exhausted the union here.
Is this related?
I believe this is the same issue:
This is useful in practice. My actual use-case involves a type projection like
function foo<T extends Id>(id: T, assocatedData: AssociatedData[T]>)
, like this:(NB: the type projection does not refine types exactly how I would like here, but that’s a separate issue.)