https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#unions-with-common-fields
keyof (A|B) = (keyof A) & (keyof B)
Showing an example:
interface Bird {
fly(): void;
layEggs(): void;
}
interface Fish {
swim(): void;
layEggs(): void;
}
declare function getSmallPet(): Fish | Bird;
let pet = getSmallPet();
pet.layEggs();
1 Example -GOOD
2 Example -GOOD
interface Birds {
flys: boolean;
layEggs: string;
}
interface Fish {
swim: number;
layEggs: string;
}
declare let k: Fish & Birds;
k = { flys:true, layEggs:"", swim:3}
3 Example -GOOD
4 Example -BROKEN
Everything is perfect until the 4th Example... It's confusing. Shouldn't it be k = { layEggs: ""} ????
PROOF:
interface Bird {
fly: number;
layEggs: string;
}
type g1 = keyof Bird
interface Fish {
swim: boolean;
layEggs: string;
}
type g2 = keyof Fish
type PetALL= keyof( Bird & Fish )
// let all1: EmployeeAll = "fly"
// let all2: EmployeeAll = "email"
// let all3: EmployeeAll = "layEggs"
type Pet = keyof( Bird | Fish )
// let only: Employee = "layEggs"
EDITOR USED https://www.typescriptlang.org/play (default settings)
CLARIFICATION OF THE QUESTION
The question is why is the type allowed in the following case:
interface Birds {
flys: boolean,
layEggs: string
}
interface Fish {
swim: number,
layEggs: string,
}
declare let k: Fish | Birds;
k = {}
Shouldn't it just be k = { layEggs: ""} ??
As seen in 4 Example -BROKEN
AND WHY DOES THIS SYNTAX WORK
5 Example -FIX