Prakhar
Prakhar

Reputation: 536

How to call function with generic params in typescript

I am trying to create something like this as below

export function f1(param1: string, param2: string) {
    console.log('Hello', param1, param2);
}

export function f2(param3: string) {
    console.log('world', param3);
}

interface Metadata {
    functionName: string;
    functionParams: any;
}

const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', {functionName: 'f1', functionParams: {param1: 'any', param2:'any1'}}],
    ['action2', {functionName: 'f2', functionParams: {param3: 'any2'}}]
])

So basically I want to call f1 or f2 function after reading it through a testMap. The idea is to store all action and their mappings against a function and execute actions in one go instead of creating multiple if and else statements.

Can somebody help I can achieve this ?

Upvotes: 1

Views: 24

Answers (1)

Connor Low
Connor Low

Reputation: 7176

You can't reference and call a function by passing its name as a string (without doing some eval black magic that I cannot in good conscience recommend). Instead, you should pass the function itself:

export function f1(param1: string, param2: string) { }

export function f2(param3: string) { }

// Change your interface to accept a function instead of a string:
interface Metadata {
    invoke: (...args: any[]) => any;
    functionParams: any[];
}

// Pass f1 or f2 (the function references) instead of 'f1' or 'f2':
const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', { invoke: f1, functionParams: ['any', 'any1'] }],
    ['action2', { invoke: f2, functionParams: ['any2'] }]
])

Playground example

Upvotes: 1

Related Questions