I am trying to create a method named Instantiate in TypeScript that will accept an object of any type.
If the object contains any properties that are classes, then the method should instantiate those classes and the return type of those properties should be the InstanceType of the respective class.
If the property is not a class, it should remain unchanged.
My issue lies in defining the correct return type. The values do not match the keys of the original object.
I need help with the TypeScript typing for this method, but I will handle the body/implementation on my own.
Here is what I have tried so far:
class Person {
name!: "John Doe"
}
class Cat {
scream!: "Help!!!"
}
const configApp = {
isComplicated: true
}
const testData = {
person: Person,
cat: Cat,
config: configApp,
} as const
type TClass = abstract new (...args: any) => any;
type TInstances<OBJ> = Record<
keyof OBJ, OBJ[keyof OBJ] extends TClass
? InstanceType<OBJ[keyof OBJ]>
: OBJ[keyof OBJ]
>;
const instantiate = <T ,>(obj:T): TInstances<T> => { return {} as any}
// Below should not error
const result = instantiate(testData);
result.person.name; // Error
result.cat.scream; // Error
result.config.isComplicated; // Error