A TypeScript function that returns the ReturnType of a specific callback function

Is it possible to define an annotation for a function that accepts a callback, and have the function return type determined by the callback's return type?

// Suppose the callback takes a number as argument
function processCallback(cb: (arg:number) => infer T /* error */ ) {
  return cb(42)
}

processCallback(x => 'bar') // expected to infer 'string' 

Answer №1

If you're looking to implement the ReturnType helper, don't forget to adjust the generic structure so it can be restricted to a function.

function executeCallback<T extends (...args: unknown[]) => unknown>(callback: T): ReturnType<T> {
  return callback(42) as ReturnType<T>;
}

const result1 = executeCallback(x => 'foo'); // string
const result2 = executeCallback(x => 123);   // number

Try it out

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

The build process encounters an issue with initializing Sentry's Vuejs (with Typescript) Integration

While attempting to build my (vue-cli-3 based) Vuejs project using gitlab-runner on my local machine, an error occurs: 98% after emitting CopyPlugin ERROR Failed to compile with 1 errors ... Property 'util' is missing in type 'VueConstruct ...

Converting a string value into an object in Javascript using a command that functions similarly to eval in Python

When working with Python, the stringValue variable is often assigned as a string: stringValue = '{"DATA":{"VERSION":1.1, "STATE":True, "STATUS":"ONLINE"}}' To convert this string into a Python di ...

Issue Encountered with @Input() in TypeScript

I'm currently working on developing an app with Angular 4 and encountered an error message when using @Input('inputProducts') products: Product[]; The specific error I received reads: [tslint] In the class "ProductListComponent", the di ...

Is there a way to display the number of search results in the CodeMirror editor?

After conducting some research on how to integrate the search result count in Codemirror like the provided image, I was unable to find any solutions. I am currently working with Angular and utilizing ngx-codemirror, which led me to realize that editing the ...

Is the runTest.ts class in the vscode-test setup ever utilized in the project? Its purpose remains unclear even in the example project

Being a novice to Typescript, JavaScript, and VScode Extensions I have set up a vscode-test following the guidelines provided here: https://code.visualstudio.com/api/working-with-extensions/testing-extension#custom-setup-with-vscodetest Based on the hel ...

What is the best way to combine individual function declarations in TypeScript?

In my project, I am currently developing a TypeScript version of the async library, specifically focusing on creating an *-as-promised version. To achieve this, I am utilizing the types provided by @types/async. One issue I have encountered is that in the ...

Is there a way to achieve this using a fresh and sleek typescript assertion function?

Presented below is the snippet of code: type Bot = BotActive | BotInactive; class BotActive { public readonly status = "active"; public interact() { console.log("Hello there!"); } } class BotInactive { public ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Obtaining a string union value dynamically during execution

Question 1: Exploring a component library, material-ui, which offers interfaces and types for customizing the css class values of each component. For the Select component, they define a type as a combination of string literals type SelectClassKey = " ...

Determining interface value based on the presence of another optional interface value

I am working with an interface that looks like this: export interface IButton { label: string; withIcon?: boolean; underlined?: boolean; selected?: boolean; iconName?: string; isLink?: boolean; href?: string; onCLick?: () => void; } My question ...

What could be causing the presence of a "strike" in my typescript code?

While transitioning my code from JavaScript to TypeScript for the first time, I noticed that some code has been struck out. Can someone explain why this is happening and what it signifies? How should I address this issue? Here's a screenshot as an exa ...

The function for utilizing useState with a callback is throwing an error stating "Type does not have

Currently, I am implementing the use of useState with a callback function: interface Props { label: string; key: string; } const [state, setState] = useState<Props[]>([]); setState((prev: Props[]) => [...pr ...

Utilize nested object models as parameters in TypeScript requests

Trying to pass request parameters using model structure in typescript. It works fine for non-nested objects, but encountering issues with nested arrays as shown below: export class exampleModel{ products: [ { name: string, ...

Incorporating TypeScript's internal references

I am currently working on defining my own model interface that extends the Sequelize model instance. However, I am encountering difficulties in referencing the Sequelize interface within my code. Specifically, I receive an error stating "Cannot find name ...

I'm experiencing an issue with my website where it appears broken when I build it, but functions properly when I use npm run dev in Next

For my project, I have utilized NextJs, Tailwind, React, and Typescript. It is all set and ready to be hosted. After using "output: export" in next.config.js and running npm run build, the process was successful. However, when viewing my website locally, I ...

Is there a way to effectively sort through Firebase database entries using Angular based on checkbox selection?

I am working on an event page where all events are displayed with a category field. This is how my database structure looks: category: - categoryName events: - eventName - category.id (stores the category id) My goal is to initially display all eve ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

simulate express-jwt middleware functions for secure routes

I am currently facing an issue with my code snippet, which looks like this: import app from '../src/app'; beforeAll(() => jest.mock('../src/middleware/auth', () => (req: Request, res: Response, next: NextFunction) => { ...

What is the best way to encapsulate a class with generic type methods within a class that also has a generic type, but without any generic type arguments on its methods?

Below is an example of the code I am working with: class Stupid { private cache: Map<any, any> = new Map(); get<T>(key: string): T { return this.cache.get(key); }; } class Smart<T> extends Stupid { get(key: string): T { s ...

I am unable to invoke this function: TypeError: this.fetchData is not a function

Whenever I try to execute this.fetchData();, I encounter the error "TypeError: this.fetchData is not a function". Initially, I suspected that the context of 'this' was lost so I attempted using bind and arrow functions without success. How can I ...