Skip to content

unions of objects are annoying #44288

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
DetachHead opened this issue May 27, 2021 · 4 comments
Closed

unions of objects are annoying #44288

DetachHead opened this issue May 27, 2021 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@DetachHead
Copy link
Contributor

Bug Report

πŸ”Ž Search Terms

Object union

πŸ•— Version & Regression Information

4.4.0-dev.20210526

⏯ Playground Link

Will add one later, writing this on my phone

πŸ’» Code

interface Foo {
    foo: number
}
interface Bar {
    bar: string
}
declare const baz: Foo | Bar

const qux = baz.bar //error: bar doesn't exist on Foo|Bar

πŸ™ Actual behavior

The type is narrowed to the intersection of the two types, making it impossible to narrow it without casting it

πŸ™‚ Expected behavior

It should narrow to something like

{
    foo?: number
    bar?: string
}
@MartinJohns
Copy link
Contributor

That would easily lead to unsoundness:

const bar = { bar: "", foo: "" };
const baz: Foo | Bar = bar

This also looks like a duplicate of #36194.

@DetachHead
Copy link
Contributor Author

In that example it would correctly fail because foo can only be number | undefined, not string. Is that the unsoundness you're referring to?

@canonic-epicure
Copy link

No, current behavior is correct. Unions are sum types. You don't know which variant of the union this value represents. Need to perform "case" matching on it (so called "pattern matching") to know that. You are asking to reduce the type-safety.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 27, 2021
@DetachHead
Copy link
Contributor Author

ah i see now. my suggestion would mean {} is a valid value, which is wrong

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