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