Skip to content

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

Closed
@avivdy

Description

@avivdy

🔎 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions