Typescript Class Constructor Self Initialization | Task

Ole Ersoy
Oct - 09  -  1 min

Scenario

We have object instances coming in over the wire with this shape:

{ p1:"hello", p2:"you" };

We want to initialize our class Test with the properties from that instance.

Approach

First we define our class:

class Test {
    p1:string;
    p2:string;
    constructor(t?:any) {
        if (t) {
            Object.assign(this, t);
        }
    }
}

Notice that we use Object.assign in the constructor to assign the instance it takes to this. Here’s an initialization demo:

let o={p1:"hello", p2:"you" };
let n = new Test(o);
console.log(n);

Note that if we have a non string property, for example a d:Date property like this:

class Test3 {
  p: string;
  d: Date;
  constructor(t: any) {
    Object.assign(this, t);
    this.d = new Date(t.d);
  }
}
let o3 = { p: 'hello', d: '2010-12-20' };
let n3 = new Test3(o2);
console.log(n3);

Then we should convert this property manually:

this.d = new Date(t.d);

Demo