Why is Object.assign({}, null) typed as {} & null in Typescript 2.6.2 instead of just {}?
1 Answer
Take a look at the TypeScript definition for Object.assign:
interface ObjectConstructor {
assign<T, U>(target: T, source: U): T & U;
assign can be parameterized, so you could have Object.assign<SourceType, TargetType>(sourceInstance, targetInstance). In this case the source and target would be a intersection type of SourceType & TargetType as specified in the type definition above.
The reason for this is that they can have different properties.
const sourceInstance = { a: 'b' };
const targetInstance = { c: 'd' };
Object.assign(sourceInstance, targetInstance); // { a: 'b', c: 'd' }
As you can see the result is the intersection of the two types. Thus, if you pass in an empty object {} and null you get the intersection type of {} & null.
null is allowed in Object.assign and is essentially ignored: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
6 Comments
Object.assign allows non-object types (or takes the "everything is an object" tack). Object.assign(2, null) works for example.Object.assign(2, null) is typed as 2 & null, when it'll only ever return a Number. Union feels wrong here.Object.assign. I'm not sure that TypeScript has the capability to create conditional types. Regardless, null as a intersectional type doesn't have any effect since null has no properties.T & U" is not a union; it's an interesection.
Object.assign({}, null)is typed?