实现说明
顶层就这几处状态:merged、reverse。
顶层对象字面量把 id、age 定成普通值——没有派生,背后也没有导入。
使用要点
- 每一步打印都带着自己的标签:
age type admits both:。
常见问题
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 状态都挂在模块顶层:merged、reverse。
核心语句
const reverse = Object.assign({}, patch, base);
const merged = Object.assign({}, base, patch);
const age: typeof merged.age = merged.age;
代码示例
type Base = { id: number; age: number };
type Patch = { age: string };
const base: Base = { id: 1, age: 30 };
const patch: Patch = { age: 'thirty' };
// assign 的返回类型是所有源类型的交集:age 同时是 number 与 string
const merged = Object.assign({}, base, patch);
const age: typeof merged.age = merged.age;
console.log(merged);
console.log('age type admits both:', age === 'thirty');
// 运行时后写覆盖先写:字符串 "thirty" 赢了数字 30
const reverse = Object.assign({}, patch, base);
console.log(reverse.age, typeof reverse.age);