I am implementing a unique class structure as shown below:
class App<objectList extends {}> {
private objects: Map<keyof objectList, any> = new Map();
add<T extends keyof objectList>(name: T, type: objectList[T]) {
this.objects.set(name, type);
this['get' + name] = () => {
return type;
}
return this;
}
}
When creating a new instance of this class, I intend to include extra objects that can be retrieved later using the function getObjectType()
on the instance.
For example:
const App = new App<{Test: string, Test2: number}>().add('Test', 'this is my test string').add('Test2', 5);
App.getTest(); // returns 'this is my test string'
App.getTest2(); // returns 5
The functionality works as intended. However, TypeScript raises an error about these functions not existing. Is there a way to strongly type a similar scenario?
UPDATE
Is it feasible to achieve the same functionality as the `add` function directly in the constructor?
class App<objectList extends {}> {
constructor(initObjects: objectList) {
/** iterate over the initObjects, create the functions **/
}
}
const inst = new App<{Test: string, Test2: number}>({
'Test': 'this is my test string',
'Test2': 5
});
inst.getTest();