2

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

1
  • How are you determining how Object.assign({}, null) is typed? Commented Jan 30, 2018 at 16:44

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

The same appears true with any non-object primitive type. I'm surprised TS is just returning a union here. Seems like there needs to be a language-level construct for filtering out non-object types.
@LeeBenson Object.assign allows non-object types (or takes the "everything is an object" tack). Object.assign(2, null) works for example.
yup, I understand. But IMO, TS isn't doing the right thing. Object.assign(2, null) is typed as 2 & null, when it'll only ever return a Number. Union feels wrong here.
@LeeBenson this is just based on TS creating a union type for the arguments to 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.
The word "union" has a specific meaning which is different from (and dual to) the word "intersection". "T & U" is not a union; it's an interesection.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.