Proper method for determining return type through the use of `infer`

I need to find out the return type based on input values, like in the code below:

type ReturnType<S> = {
    array: S extends 'number' ? number[] : S extends 'string' ? string[] : never;
    value: S extends 'number' ? number : S extends 'string' ? string : S extends 'object' ? object : never;
}

type FunctionType = {
    array: (_: 'number' | 'string') => void,
    value: (_: 'number' | 'string' | 'object') => void
};

function determineReturnType<
    T extends 'array' | 'value',
    S extends FunctionType[T] extends (_: infer Arg) => void ? Arg: never
>(t: T, s: S): ReturnType<S>[T] {}

() => {
    const x1 = determineReturnType('array', 'number') // string[] | number[]
    const x2 = determineReturnType<'array', 'number'>('array', 'number') // number[]

    const y1 = determineReturnType('value', 'number') // string | number | object
    const y2 = determineReturnType<'value', 'number'>('value', 'number') // number
}

Playground

The above code aims to determine the type of the second argument and the return type from the first argument.

A FunctionType is provided, which includes mutation functions for the second argument. The second argument's type is extracted from the argument of FunctionType using the infer keyword.

However, the compiler struggles to infer the return types of x1 and y1. Is there a way to improve the inference of generics from the second argument?

Answer №1

We can simplify this code using the Parameters utility type, which helps reduce verbosity and resolves the issue (although the reason is unclear).

function test<
    T extends 'array' | 'value',
    S extends Parameters<F[T]>[0]
>(t: T, s: S): Return<S>[T] {}

Playground

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

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...

Having trouble retrieving form values in Typescript React, only receiving HTML tag as output

I am having an issue with retrieving the form value to my useRef hook as it returns the HTML tag of the form instead. To solve this, I attempted to specify the type HTMLFormElement inside the chevrons and set null as the initial value for my useRef hook. ...

Tips for aligning the types of objects transmitted from a Web API backend to a React/Redux frontend

After creating a backend for my app using .net, I now have CRUD operations available to me. When performing a POST action, the response includes an entire new item object: {"Id":"7575c661-a40b-4161-b535-bd332edccc71","Text":"as","CreatedAt":"2018-09-13T15 ...

Discover the subsite inventory of a SharePoint site using TypeScript

Is there a way to gather all sub-sites from my SharePoint site and organize them into a list? I initially thought of using this.context.pageContext, but could not locate it. Please excuse my seemingly simple question, as I am still learning TypeScript. ...

What is the process for attaching a function to an object?

Here is the complete code: export interface IButton { click: Function; settings?: IButtonSettings; } abstract class Button implements IButton { click() {} } class ButtonReset extends Button { super() } The component looks like this: expor ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

When utilizing gapi (typescript) to send emails, the Sent box may contain incorrectly encoded email messages

When I send emails using gapi, the receiver receives them correctly. However, when I check my "Sent" box, the emails appear as Chinese gibberish characters like in this image. This issue only occurs when using non-gmail applications. If I view the Sent bo ...

Transferring information between screens in Ionic Framework 2

I'm a beginner in the world of Ionic and I've encountered an issue with my code. In my restaurant.html page, I have a list of restaurants that, when clicked, should display the full details on another page. However, it seems that the details for ...

The cloud function that is callable is currently inactive and encountering errors upon invocation

I am experiencing issues with my Cloud Function which is supposed to call a request to the URL passed to it. This is my first time using TypeScript to make a request, so I added some print calls to troubleshoot the problem. However, the first log never app ...

Tips for sending a query using the http GET method in Next.JS 14 API routes

When using the Next.js 14 API route, I am passing a page in the GET method to paginate the data fetched from my database. However, an error is thrown when trying to retrieve the query from the request: Property 'query' does not exist on type &a ...

Encountering the error message "TypeError: Cannot access property 'Token' of undefined" while compiling fm.liveswitch

The fm.liveswitch JavaScript Software Development Kit (SDK) is designed for use with both clients and your own backend "app server". It functions smoothly in the frontend thanks to webpack and babel. However, the same import statement: import liveswitch fr ...

Why aren't the child elements in my React / Framer Motion animation staggered as expected?

In my finance application, I am creating a balance overview feature. To display the content, I pass props into a single <BalanceEntry> component and then map all entries onto the page. With Framer Motion, my goal is to animate each rendered <Bala ...

Angular 6 is experiencing an issue with the functionality of the file toggle JS

Currently, I am utilizing the file toggle.js within the Urban theme. In the HTML chatbox, using the img, the file toggle.js is hardcoded and is functioning properly. However, when implementing code in Angular 6, the toggle.js is not functioning as expecte ...

The process of incorporating types into Node.js and TypeScript for handling req and res objects

Check out the repository for my project at https://github.com/Shahidkhan0786/kharidLoapp Within the project, the @types folder contains a file named (express.d.ts) where I have added some types in response. The (express.d.ts) file within the @types folde ...

Unleashing the power of Angular 7+: Extracting data from a JSON array

As a newcomer to Angular and API integration, I am facing a challenge in fetching currency exchange rates data from the NBP Web API. The JSON file structure that I'm working with looks like: https://i.stack.imgur.com/kO0Cr.png After successfully ret ...

Angular 8: Implementing Form Validation with a Boolean Flag

Within my HTML code, I have a function (change)="limitUser($event)". In Typescript, I utilize a for loop to iterate through each element and determine if the value is less than 10. If it exceeds 10, the inValid = true condition is set. All form fields in m ...

Using TypeScript to create a list of object keys defined as [key: string] key/value pairs

I'm looking to define an interface in TypeScript, but I'm unsure of how to go about it. Here's what I have in mind: export interface SomeInterface { testProp:{ [key: string]: { prop1: string; prop2?: string; prop3?: string; ...

How to define a TypeScript recursive object with a defined endpoint?

Welcome to my first question! I am currently facing an issue with defining an object to store strings in multiple languages. I am looking for a flexible solution and have considered using a nested object structure. However, I want the final object to adhe ...

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...

What is the best way to export Class methods as independent functions in TypeScript that can be dynamically assigned?

As I work on rewriting an old NPM module into TypeScript, I encountered an intriguing challenge. The existing module is structured like this - 1.1 my-module.js export function init(options) { //initialize module } export function doStuff(params) { ...