Object.assign Widens Types To An Intersection
Chained Object.assign calls give the result an intersection of every source type, so a later patch with different field shapes widens reads instead of erroring.
Code
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);Output
Captured from a sandboxed run of this snippet in the build pipeline.
{ id: 1, age: 'thirty' }
age type admits both: true
30 numberFollowing the logic along
Top-level bindings merged, reverse hold the demo state — nothing sits inside a function scope.
Module-level object literal, fixed keys: id, age.
What to watch for
- Only the runtime is demanded — zero packages, zero installation.
Applying it
The file’s steps show up in the output as age type admits both:.
Statements that matter
const reverse = Object.assign({}, patch, base);
const merged = Object.assign({}, base, patch);
const age: typeof merged.age = merged.age;
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `merged`, `reverse`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.