Code Snippet
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
Attempting to alter the runtime structure through clever TypeScript hacks is fruitless. Using as
simply instructs TypeScript to consider b
as an instance of A
, without actually converting it to one. TypeScript will only enforce type-checking rules based on this assumption during compilation.
To truly convert an object, a explicit converter function must be implemented. This function takes an object with the necessary fields and constructs a new instance of class A
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' }