• Skip to main content
  • Skip to search
  • Skip to select language
  • Get MDN Plus
  • English (US)

Object.assign()

The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object . It returns the modified target object.

The target object — what to apply the sources' properties to, which is returned after it is modified.

The source object(s) — objects containing the properties you want to apply.

Return value

The target object.

Description

Properties in the target object are overwritten by properties in the sources if they have the same key . Later sources' properties overwrite earlier ones.

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters . Therefore it assigns properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

For copying property definitions (including their enumerability) into prototypes, use Object.getOwnPropertyDescriptor() and Object.defineProperty() instead.

Both String and Symbol properties are copied.

In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised.

Note: Object.assign() does not throw on null or undefined sources.

Cloning an object

Warning for deep clone.

For deep cloning , we need to use alternatives, because Object.assign() copies property values.

If the source value is a reference to an object, it only copies the reference value.

Merging objects

Merging objects with same properties.

The properties are overwritten by other objects that have the same properties later in the parameters order.

Copying symbol-typed properties

Properties on the prototype chain and non-enumerable properties cannot be copied, primitives will be wrapped to objects, exceptions will interrupt the ongoing copying task, copying accessors, specifications, browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

TypeScript Class Constructors Tutorial

In this TypeScript tutorial we learn how to initialize an object with default values by using a special method called a constructor.

How to define a class constructor method

How to construct an object, summary: points to remember.

We can create a method that will allow us to populate properties at the same time as we create an object. It’s similar to instantiating an array.

A constructor method uses two special keywords.

First, we start by declaring the properties we want to be able to initialize with values.

Next, we define the constructor method with the keyword constructor as the method name.

Then, we add the parameters we want to initialize to the parameter list and assign them to our properties.

We would expect that we could just assign the value of the method parameter to the property, but we can’t.

We need to prefix the property with the keyword this .

The this keyword represents the calling object. We can think of it this way, when we create an object, that object’s name will replace the this keyword.

Now that we have our constructor method defined, we can use it to populate our properties with values when we create the object.

To this we add arguments for the parameters in the parentheses of the class name when we create the object.

LogRocket Blog

object assign constructor typescript

Writing a constructor in TypeScript

January 10, 2022 4 min read 1279

TypeScript Logo Over a Colorful Thrown-Paint Background

Any mature TypeScript codebase will typically make heavy use of interfaces.

They are, after all, the building blocks of adding static compile-time checks on your code, and they ensure you are sensibly using the collective/custom types you define within your code.

Interface syntax is simple, and interfaces offer a host of advantages when used in your code, such as:

Let’s learn more about constructors and how we’ll use constructors in interfaces:

Constructors

Constructor dependency injection, multiple constructors, using a constructor on an interface, benefits to using typescript interface constructors.

Constructors are also a code feature heavily used in TypeScript codebases too.

The TypeScript docs have a great example of constructor usage :

Constructors essentially allow the creation of objects from classes.

Classes act like a blueprint for typing the objects you create with the necessary properties and methods.

Constructors often make use of a code technique called dependency injection — that is key to utilizing them to their fullest potential.

This is where the dependencies necessary for the object we’re going to create are passed into the constructor.

In the above example, we see we pass in the message argument into the constructor to allow unique customization of the object:

The ability for the same class (the Greeter class) to provide different results from a method call is often called polymorphism .

A final important thing to remember when using constructors is that you cannot use multiple constructors implementations — like you can in other object-orientated languages.

An example of multiple constructors would be like so:

The above code won’t compile and logs the error Multiple constructor implementations are not allowed .

If you need to use multiple constructors to provide different functionality from a base class, there are ways of doing this, but you can only use one implementation.

If you need different constructors — there are ways to work around this though, you can type multiple constructors — you just can’t implement them.

object assign constructor typescript

Over 200k developers use LogRocket to create better digital experiences

object assign constructor typescript

A real-world example would look like:

We’ve discussed the more common use cases for utilizing constructors, but their functionality doesn’t end there.

Sometimes, as part of a design pattern or for certain use cases, developers may want to specifically create an instance variable from an interface.

A simple example of an interface we might want to construct could be:

But how we add a constructor to this type is not clear.

Even more confusingly, in the compiled JavaScript, the interface won’t even exist. It only exists to check our types and then will be totally removed , thanks to a process called type erasure.

So, let’s start with a failing example and solve it iteratively:

The error we are currently facing is:

Even though our two constructors match (in the interface versus in the class implementing the interface), it throws an error and won’t compile.

You can see in the two code examples that they are using the same type, and, by the looks of it, should compile just fine.

Adding a constructor to a TypeScript interface

The docs include an example covering this exact scenario.

Our earlier examples are failing because, according to the docs, “when a class implements an interface, only the instance side of the class is checked. Because the constructor sits in the static side, it is not included in this check.”

This reads weirdly, but it essentially means that the constructor isn’t an instance type method .

By instance type method, we’re referring to a “normal” function that would be called with obj.funcCall() existing on the object instance, as a result of using the new keyword. The constructor actually belongs to the static type.

More great articles from LogRocket:

In this case, the static type means the type it belongs to, without instantiating it, e.g., InterfaceWithConsturctor .

To fix this, we need to create two interfaces: one for the static type methods/properties and one for the instance type methods.

Our new working example, inspired by the engineering lead of TypeScript , looks like this.

This now logs as { state: { clicked: true, purchasedItems: true } } .

By using this language feature, you can create more composable objects that don’t rely on inheritance to share code.

With a constructor on the interface, you can specify that all of your types must have certain methods/properties (normal interface compliance) but also control how the types get constructed by typing the interface like you would with any other method/property.

We are relying on abstractions rather than concretions . There’s an example from the old TypeScript docs to highlight this.

The old docs are still valid TypeScript, and they’re a really clear example of what we’re discussing – so I have kept the legacy URL for clarity.

Here, we are creating a strictly typed constructor function with the arguments we need other classes to use, but at the same time, allowing it to be generic enough it fits multiple use-cases.

It also ensures we are keeping low coupling, high cohesion in our code.

I hope this has explained not only how to add a constructor onto an interface, but some of the common use cases for when and why it might be done, as well as the syntax of how you can achieve it.

It is a common enough occurrence that the docs even explain the basic approach, and it is useful to understand the two sides of static versus instance scope in the underlying JavaScript/TypeScript world.

LogRocket : Full visibility into your web and mobile apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

Share this:

object assign constructor typescript

Improving mobile design with the latest CSS viewport units

object assign constructor typescript

A guide to adding SSR to an existing Vue…

object assign constructor typescript

Using Insta for Rust snapshot testing

object assign constructor typescript

Leave a Reply Cancel reply

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Using TypeScript, and Object.assign gives me an error "property 'assign' does not exist on type 'ObjectConstructor'"

I am writing my question again because earlier it made little sense and I wasn't very clear.

I am receiving data from API that looks something like this:

So, in my code, I have a photos variable, and a method called getPhotos()

I am using infinite scroll so when I reach the bottom of the page, I call getPhotos() again.

So if the next time I call it, I get back {"photos":[{"id":2,"title":"photo_2_title"}]} , then I am trying to set this.photos to be

can someone help me with why jsfiddle.net/ca46hLw9 doesn't work? I thought assign is supposed to merge contents of an object together right?

user1354934's user avatar

3 Answers 3

Object.assign is an ECMAScript2015 feature and does not exist in ECMAScript5 and lower.

You're most likely targeting to compile your Typescript for ECMAScript5 and therefor the Object interface does not have assign defined.

You can either target ECMAScript2015 by changing your TS compiler configuration with

target: 'es6'

or you can extend the ObjectConstructor interface with the method assign

(you can add this declaration anywhere, redeclaring an interface extends it instead of overwriting it)

Or you can coerce Object to any and ignore its typing:

(<any>Object).assign( this.photos, photos )

Whichever you choose, keep in mind that if you want this to run on older browsers you need to add a polyfill. Most modern browsers are fairly close to implementing the ES2015 feature set, but they're not 100% there, meaning that some parts of your code will still fail if you rely on ES2015 functionality.

Typescript will not polyfill Object.assign when targetting ES5 or older, that is why you are getting this error. On the other hand, Babel does have polyfills in the form of plugins, which would mean you need to incorporate Babel transpilation into your build pipeline, see: https://babeljs.io/docs/plugins/transform-object-assign/

As a final option you can consider using a library as Lodash or jQuery, which have their own implementation of Object.assign (called extend )

vileRaisin's user avatar

With Typescript 2.1 or higher, you can use Object spread syntax instead.

The order of specifying spread operations determines what properties end up in the resulting object; properties in later spreads “win out” over previously created properties.

paibamboo's user avatar

For typescript version 2.0 or higher, just modify the tsconfig.json file so the "lib" section includes "es6":

Alberto S.'s user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged javascript typescript or ask your own question .

Hot Network Questions

object assign constructor typescript

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

IMAGES

  1. What is constructor function in Typescript?

    object assign constructor typescript

  2. object.assign typescript Code Example

    object assign constructor typescript

  3. javascript

    object assign constructor typescript

  4. javascript

    object assign constructor typescript

  5. typescript

    object assign constructor typescript

  6. TypeScript Interface JSON Type Inference ~ Ozkary

    object assign constructor typescript

VIDEO

  1. TypeScript 08 Asociation

  2. Learn Typescript In Arabic 2022

  3. Typescript/Javascript

  4. Introduction to single line scripting on Lemur

  5. TypeScript || Data Types || Define an Interface || Create an Array

  6. nPower Power Slice Tool tutorial

COMMENTS

  1. What is the purpose of Object.assign() in the constructor of

    The Object.assign () method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. Its used to create a shallow copy of the object and merge its properties with this which is the instance of Todo. In your given code this target object.

  2. TypeScript Class Constructors Tutorial

    constructor. this. First, we start by declaring the properties we want to be able to initialize with values. Example: class Person { firstName lastName } Next, we define the constructor method with the keyword constructor as the method name. Example: class Person { firstName lastName constructor() { } } Then, we add the parameters we want to ...

  3. Using TypeScript, and Object.assign gives me an error

    Object.assign is an ECMAScript2015 feature and does not exist in ECMAScript5 and lower. You're most likely targeting to compile your Typescript for ECMAScript5 and therefor the Object interface does not have assign defined. You can either target ECMAScript2015 by changing your TS compiler configuration with . target: 'es6'