交叉類型(Intersection Types)是將多個類型合併爲一個類型markdown
interface Person1 {
handsome: string;
}
interface Person2 {
high: string;
}
type P1P2 = Person1 & Person2;
let p: P1P2 = { handsome: "帥", high: "高" };
複製代碼
舉例:咱們提供兩撥人,一撥人都很帥、另外一撥人很高。咱們但願找到他們的交叉部分 => 又高又帥的人ui
function mixin<T, K>(a: T, b: K): T & K {
return { ...a, ...b };
}
const x = mixin({ name: "james" }, { age: 18 });
複製代碼
interface IPerson1 {
name: string;
age: number;
}
interface IPerson2 {
name: number;
age: number;
}
type person = IPerson1 & IPerson2;
let name!: never;
let person: person = { name, age: 18 }; // 兩個屬性之間 string & number的值爲never
複製代碼