Closed
Description
🔎 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
💻 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
Metadata
Metadata
Assignees
Labels
No labels