Hossein POURAKBAR
Hossein POURAKBAR

Reputation: 1181

How to initialize a typescript class from existing object?

This may be looking similar to previous questions, but I didn't find my answer, so I asked it here. My example:

Class A{
  id:number;
  name:string;
}

Class B{
  id:number;
  name:string;
  age:number;
  grade:number;
}

const b = new B {id:1, name:'John', age: 20, grade: 10}

Now I want to initialize a new instance of class A only with two attributes from class B. Something like this:

const a = b as A;

I need my result look like this:

a = {id:1, name:'John'}

Thanks,

Upvotes: 2

Views: 384

Answers (1)

pan93412
pan93412

Reputation: 196

Code

class A {
  id: number;
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }

  static toA<T extends { id: number, name: string }>({ id, name }: T): A {
    const newObject = new A(id, name);
    return newObject;
  } 
}

Explanation

It is not possible to change the runtime structure by only cheating TypeScript. as just tells TypeScript "Don't think too much, just assume b as A," and TypeScript won't do anything (including writing a B to A converter for you) except assuming the type of that object is A in the type-checking (compile) time.

So, We should write an explicit converter for it. We received any object with the required fields, then create a new A object with those fields.

Examples

class A {
  id: number;
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }

  static toA<T extends { id: number, name: string }>({ id, name }: T): A {
    const newObject = new A(id, name);
    return newObject;
  } 
}

class B extends A {
  test: number;

  constructor(id: number, name: string, test: number) {
    super(id, name);
    this.test = test;
  }
}

const b = new B(1, "hi", 2);
console.log(A.toA(b)); // A { id: 1, name: 'hi' }

Upvotes: 2

Related Questions