Skip to content

TypeScript allows assignment to a union type with missing required properties #61063

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
avivdy opened this issue Jan 28, 2025 · 2 comments
Closed

Comments

@avivdy
Copy link

avivdy commented Jan 28, 2025

🔎 Search Terms

When using a union type that includes an extended interface with required properties, TypeScript allows an object to be assigned to the union type even if it has some but not all of the properties of one of the union members. This leads to a runtime error when accessing missing properties.

🕗 Version & Regression Information

v5.7.3

⏯ Playground Link

https://www.typescriptlang.org/es/play/?ssl=21&ssc=1&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgHJwLYoN4ChnIiYQBcyAzmFKAOYDcuAvrrqJLIigArTkD2IAOrAwACwBCwKGOQQAHpBAATcmmLI8BJXEgB5GJOmiyAER0QGBAA4AbTvsNiylaiHpMWYAJ5XuvAcgAvGpYyAA+yDxQ-EIiElJiDLgIApTIcABuwBlkUTFBGoTEZADkAIJZGSUANMi29gYJxsglACoAMgBqJciMdMgA9ANofLJQUHxQyKLQECwIUBDmAKrk0AAUmdkAlEkwAK4gCGDAAQtLkKsbvtECuf4g2xr4yMAwyOsl9UgOTT2gdQeT00BEBtxAADptHpGkYITQIGAzF51rtBsNWqJgKoAO7AGw2ZAIOD7NbpZBQQ4nULQCZQF7MZhAA

💻 Code

interface Name {
  name: string;
}

interface PersonWithBirth extends Name {
  dateOfBirth: Date;
  placeOfBirth: string;
}

type Person = Name | PersonWithBirth;

const aviv: Person = { name: 'Aviv', placeOfBirth: 'TLV' }; // No error here

createUser(aviv);

function createUser(person: Person) {
  if ('placeOfBirth' in person) {
    person.dateOfBirth.getDay(); // This will cause a runtime error
  }
}

🙁 Actual behavior

TypeScript does not throw an error at the assignment of aviv, leading to a possible runtime error when accessing dateOfBirth.

🙂 Expected behavior

TypeScript should throw a type error at the assignment of aviv because it includes placeOfBirth, which is only defined in PersonWithBirth, but it is missing dateOfBirth, which is required by PersonWithBirth.

Additional information about the issue

No response

@MartinJohns
Copy link
Contributor

MartinJohns commented Jan 28, 2025

This is working as intended. Excess property checks don't happen for union types (see #20863) and your object is assignable to { name: string }.

Also, the in operator is (intentionally) unsafe (see #34975), assuming here your object is a PersonWithBirth when it's not.

@avivdy
Copy link
Author

avivdy commented Jan 28, 2025

thanks! @MartinJohns

@avivdy avivdy closed this as completed Jan 28, 2025
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