What is the purpose of Object.assign() in the constructor of a Typescript object?

object-assign polyfill
object.assign deep copy
javascript copy object without reference
typescript interface object assign
javascript add object to another object
object.assign not working
object.assign vs spread
add object to object javascript

Somewhere along the way, I added a constructor to my Todo class:

export class Todo {
  id: number;
  title: string;
  complete: boolean = false;
  editMode: boolean = false;

  constructor(values: Object = {}) {
    Object.assign(this, values);

I don't understand the purpose of the code in the constructor.

My application seems to work both with and without it, but I am hesitant to remove the code

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

This a method to easily add the values of the parameters of a class to their respective class fields where a class implements that interface or at least has a partial implantation of that interface.

interface IPerson {
  firtName: string;
  lastName: string;

class Person implements IPerson {
  public firtName!: string;
  public lastName!: string;

  constructor(params: IPerson) {
    Object.assign(this, params);

Your application works because you seem to have implemented this in such a way that the callback value of values to also be enough.

The main issue with this Hack is that Object.assign is not type safe. So using it in this way in a way goes against the point of TypeScript.

If you want to do this in a type safe fashion you are better off using a custom implementation where the type is properly checked. Something like this:

type PDM = PropertyDescriptorMap;

export class ClassSAssign<T> {
  constructor(private objectToSpread: T, private klass: T) {}

  private propertyDescriptorOptions = {
    enumerable: true,
    writable: true

  public apply(): void {
    const map = this.getPropertiesDescriptorMap();
    Object.defineProperties(this.klass, map);

  private getPropertiesDescriptorMap(): PDM {
    return Object.entries(this.objectToSpread).reduce(
      (obj: PDM, entry) => this.getPropertyDescriptorMap(obj, entry),

  private getPropertyDescriptorMap(obj: PDM, [key, value]: [string, any]): PDM {
    return {
      [key]: {

and you can use this utility like this:

class Person implements IPerson {
  public firtName!: string;
  public lastName!: string;

  constructor(params: IPerson) {
    new ClassSAssign(params, this).apply();

If you don't/can't want to use the above, I suggest you at least add some type rigour to protect your class from what values can be passed into it

interface IToDo {
  id?: number;
  title?: string;

export class Todo implements IToDo {
  public id?: number;
  public title?: string;
  public complete: boolean = false;
  public editMode: boolean = false;

  constructor(values?: IToDo) {
    Object.assign(this, values);

Object.assign(), The task of a constructor is to set up instance properties. that redundancy ( CoffeeScript and TypeScript both have ways of doing this, but I prefer this syntax): You can also use Object.assign() to (shallowly) clone an object: Object.assign () Method Among the Object constructor methods, there is a method Object.assign () which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [ [Get]] on the source and [ [Set]] on the target.

Object.assign has no type checking. An alternative would be:

const assign = <T, K extends keyof T>(...args: T[]): T =>
    args.reduce( (result, current) =>
        (Object.keys(current) as K[]).reduce((target, key) => {
            target[key] = current[key];
            return target;
        }, result)
    , args[0])

Note that if T's properties aren't optional, every object passed in must include every property. If you can guarantee the presence of every property after the function returns, you can pass in the arguments as Partial<T>, then coerce the result when you're done.

Javascript: Object.assign to assign property values for classes is not , Among the Object constructor methods, there is a method Object.assign() which is used to copy the values and properties from one or more� Spread the love Related Posts JavaScript Object Features in TypeScript — InheritanceTypeScript is a natural extension of JavaScript that’s used in many projects in place of… JavaScript Object Features in TypeScript — Methods and thisTypeScript is a natural extension of JavaScript that’s used in many projects in place of… JavaScript Object Features that we can use in TypeScript

Object.assign assigns all of the properties of the second argument to the first argument.

What the code does is if you pass an object into the constructor, it will assign those properties to the object that is being made. So for instance:

const todo = new Todo({ id: 1, title: 'hello' });
console.log(todo.title); // 'hello'

Edit: Because Object.assign is not type-safe, you should probably have the constructor accept something more specific than just an Object. I would suggest creating an interface for it.

ECMAScript 6: merging objects via Object.assign(), I've been using Object.assign to bind constructor args to this and was wondering (creates an extra object, and loops over it dynamically), so maybe don't use it in classes typescript class Example { constructor(public foo = 'alpha', public bar = ' beta', public baz constructor() { Object.assign(this, new Configurator()); this. The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.

Its just combining the two objects this and values. According to MDN

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. Consider the below example

let target = {a:1,b:2};
Object.assign(target,{x:"new prop 1",y:"new prop 2"});

Object.assign( ) in JavaScript, re: Interesting approach to map the values to a typescript object. I currently use something like class Person { firstname: string; lastname: strin gabrieltaets Just be careful with Object.assign() in that constructor. While you're� Typescript brings some awesome features that extend JavaScript in powerful ways, including the ability to define the structure of an object in a variety of ways. In your search for the best way to define objects, you will undoubtedly encounter a variety of options, class and interface being the most common.

Is using Object.assign a terrible pattern for class constructors?, Javascript Object.assign() function is used to copy the values of all own So, from the many Object constructor methods, Object.assign() is one method that is let newObj = Object.assign({}, obj); console.log('First use of Object.assign() React Native � React.js � SQL � Tableau � Tools � TypeScript � VueJS. var Child = (function { function Child() { this.name = "name"; } return Child; }()); As you can see, the name member is the only one there, and even it is only used when assigned to. Because you need the names of the members in runtime, you'll need to have them set aside, for example in an array:

Just be careful with Object.assign() in that constructor. While you're , This calls into the constructor we defined earlier, creating a new object with the Greeter In TypeScript, we can use common object-oriented patterns. class Dog extends Animal { bark () { console . log ("Woof! We create some instances of these classes and then try to assign them to each other to see what will happen. I have this function that gets an object value from a string path. In order to type this correctly, I have painstakingly added overloads. So I would need to manually update it as the requirements change:

Javascript Object Assign, Sample illustrating the use of ES6 Object.assign(). Object.assign() copies the values (of all enumerable own properties) from one or more source objects to a� TypeScript is object oriented JavaScript. TypeScript supports object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Typescript gives built in support for this concept called class. JavaScript ES5 or earlier didn’t support classes.

  • Not sure why the answer was deleted, the only part of the answer that was incorrect was apparent "equivalent" code
  • is equivalent to it may be equivalent, but you can't do that to this, and it's not really equivalent for other objects either
  • as I said, you can't assign to this like that, so that won't work at all - but even when working with other objects, it's not the same result at all ...
  • @JaromandaX I got the this part. But still can't get why both don't work same for other object. Would you mind giving an example?
  • @MaheerAli you'd lose non-enumerable properties
  • there's also this difference ... (look in the console)