3

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,

1 Answer 1

3

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' }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.