What is the best return type to use for a TypeScript function that returns an AsyncFunction?

From my experience, this code should work just fine...

let DynamicFunction = Object.getPrototypeOf(dynamic function(){}).constructor;

export function generateJsFunction(event: string, body: string[]): any {
  return new DynamicFunction(body.join("\n") + "\n//# sourceURL=" + event);
}

However, I find the "any" return type of generateJsFunction quite unsettling. What would be the proper type to return?

When using the regular Function type, it's straightforwardly just Function... but when switching to DynamicFunction, I encounter an error saying

Cannot find name 'DynamicFunction'

Answer №1

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>;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript to incorporate @fastify/oauth2

Currently in the process of importing and registering the plugin @fastify/oauth2. The dependencies being used are as follows: "devDependencies": { "@types/node": "^18.15.5", "@types/qs": "^6.9.7", ...

Utilize npm to compile TypeScript files as part of the npm build script execution

I am in the process of creating a build script using only npm, without relying on grunt or gulp. Most aspects are functioning well except for concatenating typescript files. While I can compile individual typescript files successfully, I am faced with th ...

Encountering the error "No exported member 'RouteComponentProps' in the 'react-router-dom' module while upgrading to react-router v6"

We are currently in the process of migrating legacy class-based code to the latest version 6 of react router. However, we are encountering the following error during the migration: Module '"react-router-dom"' has no exported member &a ...

Typescript code: Verify if a specific string literal is a member of a given type

I would like to create something similar to the following: type ISomeType = 'one'|'two'|'more'; const bigBigBigDataType = { ... someValue: 'bla-bla' oneOf ISomeType; ... } Although this code will run with ...

how to verify if a variable exists in TypeScript

Is there a recommended method for verifying if a variable has a value in TypeScript 4.2? My variable may contain a boolean value. I'm thinking that using if(v){} won't suffice as the condition could be disregarded if it's set to false. ...

Issue: Unable to locate the module 'nexmo' & error TS2307: 'nexmo' module not found

Currently, I am utilizing the powerful NestJs Framework alongside typescript. My task involves incorporating two-factor authentication (SMS) using the Nexmo node library. You can find further information on their website: During the development phase, ev ...

issue occurring after inserting a new parameter

I encountered an issue with my test case after adding a new parameter tiger to the method swimming. Despite passing the new parameter tiger to my test case, it continues to break. Update: I am receiving an "undefined grid" error at this line. Any suggest ...

Is it possible to create a dynamically generated key for TypeScript enums?

As a newcomer to TypeScript coming from the JavaScript world, please bear with me if my questions seem naive. What am I trying to accomplish? enum Add { PREFIX = 'ADD', ROUTE_PREFIX = 'add' } export CrudAdd { `${Add.PREFIX}_CUS ...

Displaying and concealing a subcomponent within a parent element for a set duration of time

I have a notification component that is displayed as a child component in the parent component after a button click. It automatically hides after a certain number of seconds. Here is the code I have developed: MyCode Parent component: <button (click)= ...

Error in TypeScript: The type 'Ticket[] | undefined' is not recognized as an array type

How can I add a new item to an array of objects in React state using TypeScript? Here is the code snippet in question: export type AppState = { tickets?: Ticket[], } export type Ticket = { id: string, title: string; } export type ApiC = { ...

Vue 4 and TypeScript: Dealing with the error message 'No overload matches this call'

In my Vue-Router 4 setup, I am trying to combine multiple file.ts files with the main vue-router (index.ts) using TypeScript. However, it throws an error that says "TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): ne ...

Angular - Eliminate objects from an array based on their index matching a value in a separate array

I am facing a challenge with an array of indices and an array of objects: let indices = [1,3,5] let objArray = [{name: "John"}, {name: "Jack"}, {name: "Steve"}, {name: "Margot"}, {name: "Tim" ...

Creating components with the viewContainerRef in Angular2 is functioning as expected

When attempting to load a dynamic component into the root component using viewContainerRef.createComponent, I encountered an issue where it appended to the wrong place. https://i.stack.imgur.com/lF1yT.png Here is my code: -----app.compoment.ts----- exp ...

Grab a parameter from the URL and insert it into an element before smoothly scrolling down to that

On a button, I have a URL that looks like this: www.mywebsite.com/infopage?scrollTo=section-header&#tab3 After clicking the button, it takes me to the URL above and opens up the tab labeled tab3, just as expected. However, I would like it to direct m ...

Preventing Bootstrap modal from closing when clicking outside of the modal in Angular 4

I'm working with Angular 4 and trying to prevent the model from closing when I click outside of it. Below is the code snippet I am using: <div id="confirmTaskDelete" class="modal fade" [config]=" {backdrop: 'static', keyboard: false}" ro ...

Utilizing a conditional ngIf statement in HTML or incorporating a variable within typescript for logical operations

When working with our application, we often need to display or hide a button based on specific logic. Where do you think it is best to define this logic and why? In HTML: *ngIf='logic goes here' //Or *ngIf='someBoolean' and in Type ...

Properties undefined

All of my functions are giving errors indicating that the props are not defined. The error specifically relates to the word "props" in the following functions: function PostButton(props) function PostButton2(props) function TotalVotes(props) ...

Was anticipating 1 argument, however received 5 in TypeScript

When running the code in this part, I expected to receive 0-1 arguments but ended up getting 5 instead. Do you have any suggestions for a solution? Register() { let newUser = new User(this.registerForm.value, newUser.city =this.cityid, ...

Angular examine phrases barring the inclusion of statuses within parentheses

I require some assistance. Essentially, there is a master list (arrList) and a selected list (selectedArr). I am comparing the 'id' and 'name' from the master list to those in the selected list, and then checking if they match to determ ...

Position components in Angular 2 based on an array's values

Hello all, I am a beginner in terms of Angular 2 and currently facing some obstacles. My goal is to create a board for a board game called Reversi, which has a similar layout to chess but with mono-color pieces. In order to store the necessary information, ...