Hamed Mahdizadeh
Hamed Mahdizadeh

Reputation: 976

Dynamically Call Imported Methods in Typescript

I want to dynamically call a method of my imported methods without hard coding each function name in methods like switch. Is there any solutions with something like below code?

import * as mathFn from './formula/math';

export function loadMethod(fnName: string, params: string){
   mathFn[fnName](params); 
}

I have tried this solution

type SupportedMathFunction = keyof typeof mathFn;

export function loadMethod(fnName: SupportedMathFunction, params: string){
       mathFn[fnName](params); 
}

But it is still incorrect

Is there a solutions for getting method from imported items with item name?

I get the following Error during the compiling Typescript in VSCODE Terminal:

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 don't know why this error occurred but after upgrading Node from 12.16.3 to latest 14.15.5 and running npm update this error doesn't appeared any more. but because of jasmine related error I downgraded the ts-node to 8.10.2 based on this question Jasmine-ts throwing an error about package subpath and finally the code works! with my own solution:

type SupportedMathFunction = keyof typeof mathFn;

export function loadMethod(fnName: SupportedMathFunction, params: string){
   mathFn[fnName](params); 
}

as well as @Lesiak's Solution witch is more convinient:

function loadMethod<K extends keyof typeof mathFn>(fnName: K ): typeof mathFn[K]{
  return mathFn[fnName]; 
}

Upvotes: 0

Views: 1113

Answers (1)

Lesiak
Lesiak

Reputation: 25936

I suggest the following:

function loadMethod<K extends keyof typeof mathFn>(fnName: K ): typeof mathFn[K]{
       return mathFn[fnName]; 
}

This fixes 2 problems in your code:

  • missing function keyword
  • undefined params

In addition:

  • the method returns the loaded method, and does not call it.
  • the method is correctly typed, you get right signature for each returned method

Upvotes: 1

Related Questions