microsoft / microsoft/TypeScript

Type guard does not narrow the same as if-statement

Open
#33,119 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.5.1

Search Terms:

  • Type guard function
  • If-statement guard
  • Narrow
  • Discriminated union

Code

enum E1 {
    element0 = "element0",
    element1 = "element1",
    element2 = "element2",
}
enum E2 {
    element3 = "element3",
    element4 = "element4",
    element5 = "element5",
}

declare const obj : (
    | {
        type : E1,
        data : {
            object : {
                x : "e1"
            }
        }
    }
    | {
        type : E2,
        data : {
            object : {
                x : "e2"
            }
        }
    }
);

if (obj.type == E1.element0) {
    //OK
    const type : "element0" = obj.type;
    //OK
    const x : "e1" = obj.data.object.x;
}

if (
    obj.type == E1.element0 ||
    obj.type == E1.element1 ||
    obj.type == E1.element2
) {
    //OK
    const type : "element0"|"element1"|"element2" = obj.type;
    //OK
    const x : "e1" = obj.data.object.x;
}

declare function isE1 (mixed : unknown) : mixed is E1;

if (isE1(obj.type)) {
    //OK
    const type : "element0"|"element1"|"element2" = obj.type;
    //Expected : OK
    //Actual : Error; Type '"e1" | "e2"' is not assignable to type '"e1"'.
    const x : "e1" = obj.data.object.x;
}

Expected behavior:

2nd and 3rd examples should both work.

Actual behavior:

2nd example works.
3rd example does not work.

Playground Link:

Playground

Related Issues:

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 supplied Playground reproduction and compare the direct enum checks with the user-defined isE1 type guard. Investigate TypeScript's control-flow narrowing for discriminated unions and verify the expected result: the third example should narrow obj.data.object.x to "e1". Add or update a regression test if the relevant compiler test location is identified.

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
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.