microsoft / microsoft/TypeScript
Type narrowing not working as expected in else
Open
Nobody has claimed this yet.
In Discussion
Suggestion
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
For 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
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 TypeScript Playground reproduction linked in the issue and confirm the final else branch's inferred type under strictNullChecks. Trace the compiler's control-flow narrowing for chained if/else conditions; done means the reported assignment is accepted without weakening the other narrowing behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100