1

I was working with some union types and found this pattern that I am not sure how it works.

Lets suppose we have a type like this:

type Person = { name?: string; age: number; gender: string };
type Name = { name: string };
type Comb = Person | Name;

Now, lets declare some variables of that type and see which ones show an error:

 const object1: Comb = { name: 'pedro' }; //No error, it is Name type
 const object2: Comb = { age: 3, gender: 'male' }; //No error, it is Person type
 const object3: Comb = { age: 3 }; //Error, it needs 'gender' to be type Person
 const object4: Comb = { age: 3, name: 'pedro' }; //No error??? Why?? 

Now the last one is the one I don't understand, It is not a Person because gender is required and is not present, it is also not a Name because it has properties that are not defined in Name type.

Why does it pass without adding the gender property? Or without removing the age? How does this work? The official docs don't address anything like this if am not mistaken.

Thanks

BraisC
  • 199
  • 2
  • 10
  • I think it's because the types are combined. It's not an "or" situation. – evolutionxbox Jul 22 '22 at 13:02
  • "*it is also not a `Name` because it has properties that are not defined in `Name` type*" - it's *more* than a `Name`, yes, but that doesn't matter, it's still a valid `Name`. See [structural subtyping](https://www.typescriptlang.org/docs/handbook/type-compatibility.html) and [excess property checks](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks) – Bergi Jul 22 '22 at 13:15
  • Excess property checks only kick in for specific situations, and (unfortunately in my opinion) they do not warn on properties that are mentioned in *some* member of a union. See the answer to the linked question for more information. – jcalz Jul 22 '22 at 13:38

0 Answers0