microsoft / microsoft/TypeScript
This narrowing typeguard effect bleeds into subsequent statments on a type with bivariant type-parameter
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.4.0-dev.201xxxxx (although 3.3 is also impacted)
Search Terms: this type guards
If we create a type-guard that narrows this on a type that has a type-parameter that is present only in a bivariant position, the effect of the type guard persists outside of the guarded block.
Code
type GetKnownKeys<G> = G extends GuardedMap<infer KnownKeys> ? KnownKeys: never;
interface GuardedMap<KnownKeys extends string> {
get(k: KnownKeys): number;
has<S extends string>(k: S): this is GuardedMap<S | GetKnownKeys<this>>;
}
declare let map: GuardedMap<never>;
map.get('bar') // err, as expected
if (map.has('foo')) {
map.get('foo').toExponential(); // ok as expected
if(map.has('bar'))
{
map.get('foo').toExponential(); // ok as expected
map.get('bar').toExponential(); // ok as expected
}
map.get('bar').toExponential(); /// OK!?!?! WHY ?!
}
map.get('bar') // OK ?!
Expected behavior:
Type guard only impacts the guarded block.
Actual behavior:
The effect of the type guard bleads into all subsequent statements. (marked with OK!?!?! and OK?!)
Note: With strictFunctionTypes on, declaring get as get: (k: KnownKeys) => number; makes the code work as expected.
Playground Link: link
Related Issues: Similar to #14817
Found this while playing with a solution for #9619
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
Reproduce the narrowing leak in the linked TypeScript Playground using the provided GuardedMap example. Trace the compiler's control-flow handling for this type guards and bivariant type parameters; done means narrowing remains confined to the guarded block and the post-block map.get('bar') is rejected, with regression coverage.
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