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

Unsoundness in union of object types #45614

Closed
hanayashiki opened this issue Aug 28, 2021 · 2 comments
Closed

Unsoundness in union of object types #45614

hanayashiki opened this issue Aug 28, 2021 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@hanayashiki
Copy link

hanayashiki commented Aug 28, 2021

Bug Report

πŸ”Ž Search Terms

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about union types

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type V = {
    a: {
        c: string,
    },
    b: number,
} | {
    b: number,
}

const v: V = {
    a: undefined,
    b: 1
}

if ('a' in v) {
    console.log(v.a.c);  // In runtime there would be an error of accessing undefined
}

πŸ™ Actual behavior

No error is found

πŸ™‚ Expected behavior

I know TS is not built to be sound, and it is more a static analytic tool for JavaScript. But is this behavior expected?

In this case, 'a' in v does not indicate v.a is { a: {.c: string } }, because v could be anything containing b: number, but we don't make any assumptions about a, since as long as b: number exists then v is V.

I also find if we initialize v as

const v: V = {
    a: 0,
    b: 1
}

It returns with an error Type 'number' is not assignable to type '{ c: string; }'., even though, it is a subtype of { b: number }.

So, it means "only undefined can be assigned to a"?

It seems a: undefined is a special case for object literals and union types, but it this documented anywhere?

Thanks in advance.

@MartinJohns
Copy link
Contributor

Duplicate of #34975.

@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Aug 30, 2021
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

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

4 participants