microsoft / microsoft/TypeScript

Indexed this types don't narrow when their referenced property narrows

Open
#26,759 0 comments 1 reaction 0 assignees View on GitHub

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

TypeScript Version: 3.1.0-dev.20180829

Search Terms: this index narrowing generics

Code

type Keys = 'string' | 'number';
type Switch<T extends Keys> =
	T extends 'string' ? string :
	T extends 'number' ? number :
	never;

interface Main<T extends Keys> {
	kind: T;
	value: Switch<this['kind']>;
}

let x: Main<Keys> = null as any;

x.kind;
x.value;
if (x.kind === 'string') {
	x.kind; // Narrowed to "string"
	x.value;
} else {
	x.kind; // Narrowed to "number"
	x.value;
}

Expected behavior:
In the first if block, x.value should be of type string. In the second if block, x.value should be of type number.

Actual behavior:
In both cases x.value is not narrowed, despite x.kind narrowing successfully.

Related Issues: #24085

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the TypeScript reproducer in the issue and compare its behavior with related issue #24085. Trace how narrowing of x.kind affects the indexed this['kind'] type, then verify that the two branches report string and number for x.value respectively.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.