In my typescript project, I am looking to create a factory function that can generate a new object instance based on an existing object and a set of properties to populate it with. Essentially, I want to be able to convert one type of object into another related type. Here is an example of how I would like to use this function:
const newA = A.from({ a: 1 });
const newC = C.from({ a: 1, b: 2, c: 9 });
I have already implemented this functionality, but I believe there may be a simpler way using Object.create. However, the current implementation only works when inheriting from the base class, which is not ideal for me as I don't want to duplicate the function every time I create a new subclass.
class A {
static from(data: Partial<A>): A {
const o = Object.create(A);
Object.assign(o, data);
return o;
}
}
I have tried to make the function more generic so that I can use it without specifying the class each time. While the following code snippet does work, I still need to explicitly define the class when calling the function:
class A {
...
static from<T extends A>(data: Partial<T>): T {
const o = Object.create(this);
Object.assign(o, data);
return o;
}
}
const newC = C.from<C>({ ... });
I was hoping to find a way to incorporate generics in a better way, something like this:
class A {
static from<T extends this>(data: Partial<T>): A {
const o = Object.create(this);
Object.assign(o, data);
return o;
}
}
const new C = C.from({ ... });
I believe there should be a way to achieve this using inferred class types during compile time, but I haven't been able to figure out the correct syntax. Is this approach considered acceptable or are there better alternatives?
Any guidance on this matter would be greatly appreciated!