I have a *.ts file with lots of exported functions like:
export function newItemFoo() {
return {foo: 0, bar: '', baz: true};
}
export function newItemBar() {
return {foo: 0, bar: ''};
}
export function newItemXXX() {
return {xxx: 0};
}
I want to make a "magic method" (in the same *.ts) that can call one of those methods by name, eg:
export function magicMethod(name: string) {
const newEmptyFunc = new Function(`return new${name}()`);
return newEmptyFunc();
}
magicMethod('ItemFoo');
but it raise an error
Error: newItemFoo is not defined
It works with eval:
export function magicMethod(name: string) {
return eval(`newEmpty${name}()`);
}
magicMethod('ItemFoo');
How do I call a function by string name with new Function()?