示例工程 08-unions-intersections
08-unions-intersections/03-intersection/src/main.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// 演示:交叉类型要求同时满足两侧;合并对象时保留两组属性
export type Named = { name: string };
export type Aged = { age: number };
export type Person = Named & Aged;
export function makePerson(name: string, age: number): Person {
return { name, age };
}
export function merge<A extends object, B extends object>(a: A, b: B): A & B {
return { ...a, ...b };
}
export function run(log: (msg: string) => void = console.log): string[] {
const person = makePerson('Ada', 36);
const merged = merge({ role: 'admin' }, { level: 3 });
const lines = [
`${person.name}:${person.age}`,
`${merged.role}:${merged.level}`,
];
for (const line of lines) {
log(line);
}
return lines;
}