Type narrowing not working as expected in else
See original GitHub issueFor the following code with strictNullChecks
enabled:
interface Base {
a: {} | null;
b: {} | null;
}
function test(base: Base): void {
if (!base.a && !base.b) {
const result: null = null;
} else if (!base.a && base.b) {
const result: {} = base.b;
} else if (base.a && !base.b) {
const result: {} = base.a;
} else {
const result: {} = base.b;
}
}
I’m seeing this error on the last result:
Type '{} | null' is not assignable to type '{}'.
Type 'null' is not assignable to type '{}'.
I expect it to work as the else implies:
!(!base.a && !base.b) && !(!base.a && base.b) && !(base.a && !base.b)
= (base.a || base.b) && (base.a || !base.b) && (!base.a || base.b)
= (base.a || base.b) && (base.a) && (base.b)
note: !base.b and !base.a are canceled out as the expression cannot be true if one
of them is false
= base.a && base.b
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (4 by maintainers)
Top Results From Across the Web
Type Narrowing not working as expected with generic ...
The reason why it's not narrowed is explained in this answer. Hacky way to narrow the type correctly: type Result<T> = T extends...
Read more >Documentation - Narrowing - TypeScript
TypeScript follows possible paths of execution that our programs can take to analyze the most specific possible type of a value at a...
Read more >Type narrowing not working as expected #11245 - GitHub
TypeScript Version: 2.0.2 RC ; Code This code fails: ; Expected behavior: The narrowing should recognize that arg must be a string[] when...
Read more >Type-Safe TypeScript with Type Narrowing - Rainer Hahnekamp
Whenever we deal with a variable that can be of multiple types, like an unknown or a union type, we can apply type...
Read more >Narrowing
Narrowing. Imagine we have a function called padLeft . function padLeft(padding: number | string, input: string): string { throw new Error("Not implemented ...
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
Sorry, I don’t know why this was labeled as a question.
@DanielRosenwasser I think this is labelled incorrectly and shouldn’t have been closed, it never really got an answer on why or why not from a maintainer.