Skip to content

Strange narrowing behavior on objects using discriminator property Β #49334

Closed
@joeldentici

Description

@joeldentici

Bug Report

πŸ”Ž Search Terms

discriminated union narrowing

πŸ•— Version & Regression Information

4.6.2

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about discriminated unions and narrowing

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

The linked example above shows how to reproduce. The broken function in the example has x on line 35 inferred as { readonly type: "foo"; }. It should be narrowed in this position to never.

This behavior prevents the following common pattern from being used when you only have 1 member of a discriminated union (which is realistic if you are building the "first type" and plan to build others later):

// utility for catching non-exhaustive switches
class UnexpectedCase extends Error {
    constructor(value: never) {
         super(`Did not expect to reach case: ${JSON.stringify(value)}`);
    }
}

interface FirstType { type: 'FirstType' }

type Types = FirstType; // later we will add 'SecondType' and so on

function transform(x: Types) {
    switch (x.type) {
        case 'FirstType':
            return // create something else
        default:
            // we want to get a type error here in the future when we have missing cases, but we are already getting
            // one now because the type system isn't narrowing `x` to `never`
            throw new UnexpectedCase(x); // TS error: argument of type 'FirstType' is not assignable to never
    }
}

Yes I'm aware that this technically isn't a discriminated union, but it shouldn't make a difference. The point is that the type system isn't narrowing the type of a variable to never when it clearly (in a statically knowable way) cannot have a value in this branch.

πŸ™ Actual behavior

The type system is not narrowing x to never in the example above in the default case, even though this case cannot be reached.

πŸ™‚ Expected behavior

x should be narrowed to never in the default case because that code cannot be reached. This is the only sensible behavior if we want to say never is a bottom type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions