- 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.
- Polyfill of Object.assign in core-js
- Object.defineProperties()
- Enumerability and ownership of properties
- Spread in object literals
- Course List
- Introduction to TypeScript
- Environment Setup
- Workspace & first app
- Basic Syntax
- Variables & Constants
- Conditional Control
- if, else if, else & switch
- Iteration Control
- for, while, do-while loops
- Intermediate
- Map Collections
- Object Oriented Programming
- OOP: Classes & Objects
- OOP: Standalone Objects
- OOP: Constructors
- OOP: Property Modifiers
- OOP: Access Modifiers
- OOP: Parameter Properties
- OOP: Getters & Setters
- OOP: Static methods
- OOP: Index Signatures
- OOP: Inheritance
- OOP: Composition
- Compilation Config (tsconfig.json)
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.
- constructor
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.
- To create a class constructor we define a method called constructor in the class with parameters for the properties we want to initialize with data.
- The properties that we want to initialize must be declared before we try to use them in the constructor.
- The this keyword refers to the calling object.
- Define a class constructor
- Construct an object

- Start monitoring for free
Writing a constructor in TypeScript
January 10, 2022 4 min read 1279

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:
- Produce simple, easily understood error messages
- Sometimes compile faster than type definitions
- Used heavily by the TypeScript community, so they are a common best practice, (the TypeScript documentation utilizes them heavily also)
- The TypeScript team endorses interfaces , too. Daniel Rosenwasser, TypeScript’s program manager, has endorsed interfaces over type
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.

Over 200k developers use LogRocket to create better digital experiences

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:
- Don't miss a moment with The Replay , a curated newsletter from LogRocket
- Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
- Use React's useEffect to optimize your application's performance
- Switch between multiple versions of Node
- Discover how to animate your React app with AnimXYZ
- Explore Tauri , a new framework for building binaries
- Compare NestJS vs. Express.js
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 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:
- Uncategorized
- #typescript
Improving mobile design with the latest CSS viewport units

A guide to adding SSR to an existing Vue…

Using Insta for Rust snapshot testing

Leave a Reply Cancel reply
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
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?
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 )
- would the extending objectconstructor act as a polyfill? – user1354934 Aug 9, 2016 at 21:12
- Hi I am wondering if I am doing something wrong. I tested with simple object, { a: 1 }, and tried to do const test = Object.assign({ a: 1}, {b: 2}); but when I console.log(test); I see only {b: 2} – user1354934 Aug 9, 2016 at 21:29
- @user1354934 This is because you are trying to do a deep clone (objects inside of objects). Object.assign apparantly only does shallow clones. See the 2nd example on the MDN documentation: developer.mozilla.org/en/docs/Web/JavaScript/Reference/… – vileRaisin Aug 10, 2016 at 13:04
- Bit late, but I think Angular 2 does polyfill Object.Assign - at least if you use Angular CLI. There is a src/polyfills.ts file, that includes a reference to core-js/es6/object, which in turn seems to include the Object.Assign polyfill. – JonRed Feb 7, 2017 at 17:18
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.

- 7 E.g: const opts = { ...defaults, ...options } – joseluisq Dec 31, 2017 at 12:00
- It's different when obj is created from a new expression. – Yang Bo Nov 7, 2018 at 7:04
- Unfortunately this won't work when "obj" is a constant. Otherwise it is a good solution. – Ledda Jul 11, 2020 at 12:41
For typescript version 2.0 or higher, just modify the tsconfig.json file so the "lib" section includes "es6":
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 .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Why are physically impossible and logically impossible concepts considered separate in terms of probability?
- Stored Procedure Tuning Help
- What sort of strategies would a medieval military use against a fantasy giant?
- Movie with vikings/warriors fighting an alien that looks like a wolf with tentacles
- How is Jesus "υἱὸς ὑψίστου κληθήσεται" (Luke 1:32 NAS28) different from a prophet (παιδίον, προφήτης ὑψίστου κληθήσῃ Luke 1:76 NAS28)?
- How to react to a student’s panic attack in an oral exam?
- What is the point of Thrower's Bandolier?
- Is there a single-word adjective for "having exceptionally strong moral principles"?
- How to prove that the supernatural or paranormal doesn't exist?
- Is it suspicious or odd to stand by the gate of a GA airport watching the planes?
- How to handle missing value if imputation doesnt make sense
- Lots of pick movement
- Recovering from a blunder I made while emailing a professor
- How does fire heat air?
- Are there tables of wastage rates for different fruit and veg?
- Theoretically Correct vs Practical Notation
- What is the correct way to screw wall and ceiling drywalls?
- Knocking Out Zombies
- Why is there a voltage on my HDMI and coaxial cables?
- What video game is Charlie playing in Poker Face S01E07?
- How to tell which packages are held back due to phased updates
- Does Counterspell prevent from any further spells being cast on a given turn?
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- nicematrix: add ttfamily in the last-col
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
VIDEO
COMMENTS
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.
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 ...
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'