Skip to content

Issue narrowing tagged unions with temporary const #31037

Closed

Description

@kyleshay

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms: Narrowing, "Tagged Unions"

Code

interface Square {
    kind: 'square';
    size: number;
}
interface Circle {
    kind: 'circle';
    radius: number;
}
type Shape = Square | Circle;

// works as expected (s.kind) does the correct narrowing
function areaWorking(s: Shape) {
    switch (s.kind) {
        case 'square': return s.size * s.size;
        case 'circle': return Math.PI * s.radius ** 2;
    }
}

// When saving s.kind to a const variable, narrowing does not work
function area(s: Shape) {
    const {kind} = s; // same as const kind = s.kind;
    switch (kind) {
        case 'square': return s.size * s.size; // Property 'size' does not exist on type [Shape|Circle].
        case 'circle': return Math.PI * s.radius ** 2; // Property 'radius' does not exist on type [Shape|Square].
    }
}

Expected behavior:
I would expect to be able to pull the kind property from the Shape object into a const and the narrowing to work as expected.

Actual behavior:
Narrowing does not work, I need have the switch() go off of the variable passed in.

Playground Link: TS Playground

Related Issues: #18758

Activity

  1. changed the title [-]Issue narrowing tagged unions with intermediary const[/-] [+]Issue narrowing tagged unions with temporary const[/+] on Apr 19, 2019
  2. jack-williams commented on Apr 19, 2019

    @jack-williams
    Collaborator

    Narrowing isn’t tracked across variables; the issue tracking this is here: #12184. You’ll find related/duplicate issues linked to that one.

  3. kyleshay commented on Apr 19, 2019

    @kyleshay
    Author

    Thanks!

  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions