Nikos Iliakis
Nikos Iliakis

Reputation: 167

Create dynamically overloaded functions in typescript

So I'm creating some functions dynamically based on some input from the users. One input is the name of each function. I would like to be able to create (and expose) some functions with the same name but different parameters.

const input = [
      {name: 'mul', paramTypes: { par1: 'number', par2: 'number'},
      {name: 'add', paramTypes: { par1: 'number', par2: 'number'},
      {name: 'add', paramTypes: { par1: 'string', par2: 'string'}
];

let functionsToExpose = [];

for (fun in input){

     functionsToExpose[fun.name] = (...arguments)=>{...}

}
return functionsToExpose;

I would like to create two add functions, one for numbers and one for strings (concatenation). Currently, only one is created. Is there a way I could create and expose both?

Upvotes: 0

Views: 247

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075925

So I'm creating some functions dynamically based on some input from the users.

Then TypeScript won't be able to help with this part, because TypeScript works at compile-time, and you won't have the data from the users except at runtime.

I would like to create two add functions, one for numbers and one for strings (concatenation).

The only way you can do that in JavaScript is if you store the functions in different places. It's impossible, in JavaScript, to have more than one function associated with the same identifier in the same scope. (The functions can have the same name as far as the name property on them goes, but they have to be referenced by distinct things.) TypeScript could let it seem like you had function overloads, but there would be only one actual function (the implementation), and again TypeScript type information is a compile-time construct, not a runtime construct.

There are various other things you can do:

  • Include the parameter types in the name
  • Organize the functions into separate objects (numbers.add, strings.add)
  • Create an array of functions

Upvotes: 2

Related Questions