microsoft / microsoft/TypeScript
Type not narrowed by === when equivalent type guard works
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 3.7.5, also tested on 3.9.0-dev.20200212
Search Terms: equals, type guard, type parameter, narrowing
Code
type AorB = 'a' | 'b';
function isA(t: AorB): t is 'a' {
return t === 'a';
}
function test<T extends AorB>(arg: T) {
if (isA(arg)) {
let a1: T & 'a' = arg; // ok
}
if (arg === 'a') {
let a2: T & 'a' = arg; // error
}
}
Expected behavior: The condition arg === 'a' should narrow the type of arg to T & 'a' in the second if block, in the same way as the equivalent type guard function does.
Actual behavior: The type of arg is not narrowed in the second if block.
Playground Link: Playground Link
Related Issues: N/A
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 by reproducing the TypeScript 3.7.5 or 3.9.0-dev.20200212 behavior from the issue's TypeScript snippet, comparing the direct equality check with the equivalent type guard. Trace the compiler's type-narrowing handling for generic type parameters; done means arg === 'a' permits arg to be assigned to T & 'a' without an error.
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
- Clearly specified
- Newbie friendliness
- 38/100