Skip to content

Property not checked in union of objects #30631

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

Closed
OliverJAsh opened this issue Mar 28, 2019 · 2 comments
Closed

Property not checked in union of objects #30631

OliverJAsh opened this issue Mar 28, 2019 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@OliverJAsh
Copy link
Contributor

TypeScript Version: 3.3.3333

Search Terms:

Code

type MyPhotoA = { id: number };
type MyPhotoB = MyPhotoA & { userId: number };

type MyPhoto = MyPhotoA | MyPhotoB;

declare const myPhoto: MyPhoto;

const myPhoto2: MyPhoto = {
    ...myPhoto,
    // Expected type error but got none. `userId` should be string
    userId: {},
};

if ('userId' in myPhoto2) {
    // No type error, but runtime exception!! Very bad…
    myPhoto2.userId.toFixed();
}

IIUC, this is because TS considers myPhoto2 assignable to MyPhotoA with an excess property userId.

Shouldn't TS check that the excess property is not used in other members of the union?

@OliverJAsh OliverJAsh changed the title Property not checked for union type Property not checked in union of objects Mar 28, 2019
@jack-williams
Copy link
Collaborator

Think this is a duplicate of #20863.

The real design issue here is that excess property checking runs exclusively before further type-checking, delivering a yes/no answer. To correctly check this case you need excess property checking to effectively prune off MyPhotoA from the union MyPhoto when comparing the types of the properties. For that to work you either need excess property checking to work in tandem with type-checking, or you need excess property checking to return more than just yes/no.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 1, 2019
@OliverJAsh
Copy link
Contributor Author

Closing due to duplicate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants