microsoft / microsoft/TypeScript

Type not narrowed by === when equivalent type guard works

Open
#36,772 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow Rescheduled
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

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 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.