We can start by refining the type of AsyncFunction
. Although the built-in typings suggest it's any
, we can specify that it is actually a FunctionConstructor
.
let AsyncFunction: FunctionConstructor = Object.getPrototypeOf(async function () {}).constructor;
Once we have defined it as such, we can utilize it similarly to how we would with the standard Function
constructor.
const createJsFunction = new AsyncFunction('event', 'body', `
await body.join('\\n') + '\\n//# sourceURL=' + event
`);
(Take note of the double backslash within the template string.)
Although this approach works, the inferred type for createJsFunction
will be simply Function
. This is due to the difficulty for the type system in predicting the result at compile-time.
If we are aware of the expected signature, we can inform TypeScript by utilizing a type assertion (in this case:
as (event: string, body: string[]) => Promise<string>
):
const createJsFunction = new AsyncFunction('event', 'body', `
body.join('\\n') + '\\n//# sourceURL=' + event
`) as (event: string, body: string[]) => Promise<string>;
As mentioned in your comment, one advantage of employing the AsyncFunction
constructor is the ability to include await
statements within the constructed function.
const createJsFunction = new AsyncFunction('event', 'body', `
await body.join('\\n') + '\\n//# sourceURL=' + event
`) as (event: string, body: string[]) => Promise<void>;