Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue narrowing tagged unions with temporary const #31037

Closed
kyleshay opened this issue Apr 19, 2019 · 2 comments · Fixed by #44730
Closed

Issue narrowing tagged unions with temporary const #31037

kyleshay opened this issue Apr 19, 2019 · 2 comments · Fixed by #44730

Comments

@kyleshay
Copy link

kyleshay commented Apr 19, 2019

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

@kyleshay kyleshay changed the title Issue narrowing tagged unions with intermediary const Issue narrowing tagged unions with temporary const Apr 19, 2019
@jack-williams
Copy link
Collaborator

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

@kyleshay
Copy link
Author

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants