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

undefined | string property of object incorrectly narrowed to string in union type #53264

Closed
everhardt opened this issue Mar 15, 2023 · 2 comments

Comments

@everhardt
Copy link

Bug Report

πŸ”Ž Search Terms

union undefined incorrectly narrowed

πŸ•— Version & Regression Information

This is the behavior in every version I tried (back to 3.3.3), and I reviewed the FAQ for entries about bugs, undefined and unions.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

let a: string | undefined;

type B_1 = { a: string, c: 'test', d: 'yeah' };
type B_2 = { c: 'test'}
type B = B_1 | B_2;

// this should complain that
// - property a should not not exist
// - or property a should be string and property d is missing
const b: B = { a, c: 'test'};

if ('a' in b) {
    // because of this issue, b is narrowed to B_1 here, while a is undefined and d is not present
    console.log(b);
}

πŸ™ Actual behavior

const b: B = { a, c: 'test'}; does not throw a TS error.

πŸ™‚ Expected behavior

const b: B = { a, c: 'test'}; throws a TS error.

@MartinJohns
Copy link
Contributor

The assignment is allowed, because { a, c: 'test' } is a valid B (specifically, it's a valid B_2). Excess property checks is not performed for union types, see #51873.

This unfortunately leads to an intentional unsoundness using the in operator, see #34975.

@everhardt
Copy link
Author

Thanks for your quick reply! I think this issue can then be closed as it doesn't add much to the two issues you mentioned. Sorry for wasting your time.

@everhardt everhardt closed this as not planned Won't fix, can't repro, duplicate, stale Mar 15, 2023
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

No branches or pull requests

2 participants