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

Partial type fails to narrow in spite of check for undefined II #31495

Closed
NoelAbrahams opened this issue May 21, 2019 · 7 comments
Closed

Partial type fails to narrow in spite of check for undefined II #31495

NoelAbrahams opened this issue May 21, 2019 · 7 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@NoelAbrahams
Copy link

TypeScript Version: 3.4.0
Search Terms: Partial switch

Code

const enum BarEnum {
    bar1 = 1,
    bar2 = 2,
}

type TypeBar1 = {

    foo: BarEnum.bar1;
    array: number[];
};

type TypeBar2 = {

    foo: BarEnum.bar2;
    array: number[];
};

type UnionOfBar = TypeBar1 | TypeBar2;

const value: Partial<UnionOfBar> = {} as any;

if (value.array) {

    value.array.toString(); // Okay

    switch (value.foo) {

        case BarEnum.bar1:
            value.array.toString(); // Error: Object is possibly undefined
            break;
    }
}

Expected behavior:
No compiler error

Actual behavior:
The compiler complains of value.array being undefined

Playground Link:
Not able to reproduce on the playground. I think this is a bug in 3.4.

Related Issues:
This is another version of the bug reported here: #29496

@j-oliveras
Copy link
Contributor

It can be reproduced on playground enabling strictNullChecks under Options.

Probably related to #9998.

@jack-williams
Copy link
Collaborator

Narrowing by discriminant (which is happening at value.foo in the switch) narrows from the declared type of value, thus ignoring the previous property narrowing obtained from value.array. This is probably a design limitation / working as intended.

@NoelAbrahams
Copy link
Author

It may be a design limitation, but it certainly cannot be working as intended - unless the intention is to surprise the user!

@madhavmalhotra-3089
Copy link

I am facing the same issue.

@sigorilla
Copy link

+1, example

@threehams
Copy link

The examples in this issue are fixed in 3.8. I don't know what change fixed them, though.

@NoelAbrahams
Copy link
Author

@threehams, you're right: it's been fixed. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

7 participants