bereal
bereal

Reputation: 34282

Formal arguments of a dynamically created function in Typescript

In Javascript you can create a function dynamically, like this:

const func = new Function(['arg'], 'console.log(arg)');

So that it can be called with the given arguments: func('Hello'). However, in Typescript the Function constructor seems to accept only one argument, the function body. Is there a way to provide formal arguments to a dynamically generated function?

(Security note: the code is coming from a trustworthy source and what it may contain is verified to be very limited.)

Upvotes: 0

Views: 135

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249556

The Function constructor takes a variable number of strings just like the typescript definition states, with the last one being the function body:

new Function ([arg1[, arg2[, ...argN]],] functionBody)

This is according to the docs

Browser implementations are probably more permissive, but typescript adheres to the spec.

The simplest solution is to call the function as intended:

const func = new Function('arg', 'console.log(arg)');

Or if you already have the array of arguments:

const func = new Function(...['arg'].concat('console.log(arg)'));

Upvotes: 4

Ali Usman
Ali Usman

Reputation: 1

Rather than using the Function constructor for creating a new function, just assign a function to variable like this:

const func = function(arg) {
    console.log(arg);
}

Assigning a function this way is known as a Function Expression and it is used extensively in JavaScript. Assigning it this way you can add as many arguments as required.

const func = function(arg1, arg2, arg3) {
    console.log(arg1);
    console.log(arg2);
    console.log(arg3);
}

Upvotes: 0

Related Questions