Is there a way to dynamically call a method from my imported functions without hard-coding each function name in a switch statement? I'm looking for a solution like the following code:
import * as mathFn from './formula/math';
export function loadMethod(fnName: string, params: string){
mathFn[fnName](params);
}
I've attempted the following solution:
type SupportedMathFunction = keyof typeof mathFn;
export function loadMethod(fnName: SupportedMathFunction, params: string){
mathFn[fnName](params);
}
However, this approach is still giving errors.
Is there a way to retrieve methods from imported items using their names?
When compiling Typescript in VSCODE Terminal, I encountered the following Error:
SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:1047:16)
at Module._compile (internal/modules/cjs/loader.js:1097:27)
at Module.m._compile (...\node_modules\ts-node\src\index.ts:1043:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Object.require.extensions.<computed> [as .ts] (...\node_modules\ts-node\src\index.ts:1046:12)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require (internal/modules/cjs/loader.js:1019:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (...\src\functions.ts:11:1)
Update:
I resolved the error by upgrading Node from 12.16.3 to the latest version 14.15.5 and running npm update. Although, I faced Jasmine related issues, so I downgraded ts-node to version 8.10.2 based on this question Jasmine-ts throwing an error about package subpath, which ultimately allowed the code to work with my own solution:
type SupportedMathFunction = keyof typeof mathFn;
export function loadMethod(fnName: SupportedMathFunction, params: string){
mathFn[fnName](params);
}
Furthermore, @Lesiak's solution proved to be more convenient:
function loadMethod<K extends keyof typeof mathFn>(fnName: K ): typeof mathFn[K]{
return mathFn[fnName];
}