Lee Benson
Lee Benson

Reputation: 11629

Typescript: Invalid Object.assign type?

Why is Object.assign({}, null) typed as {} & null in Typescript 2.6.2 instead of just {}?

Upvotes: 2

Views: 538

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191809

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

Upvotes: 2

Related Questions