Map one object to another of extended class in nestJS

Viewed 467

I have a class lets say class A:

class A{
    x: string,
    y: string,
    z:string
}

and another class Y

import { PickType } from '@nestjs/swagger';
    
class B extends PickType(A, ['x', 'y'] as const) {
     p: string;
}

Now I want to convert the object of class X to Y in an efficient way and add Property P. How can I do that?

PS: One way is to create a new instance of Y and assign the values one by one, maybe create a method in X or Y for conversion and do the same i.e copy values one by one but I am trying to find a more efficient way as that seems to violate DRY.

1 Answers

if I got you, you can define A as type not as a class, same for B

interface A {
    x: string,
    y: string,
    z:string 
}

interface B extends A {
    p: string;
}

const a: A = {
    x: '1',
    y: '2',
    z: '3'
};

const b: B = {
    ...a,
    p: '8'
}
Related