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' }