Can we determine the return type of a function based on the specific parameters it is called with?

When working with generated APIs, such as openapi-fetch, our code may look something like this:

import {paths} from "./the-generated-types"; 
import createClient from "openapi-fetch"; 

const client = createClient<paths>(); 


// Using the client:
client.GET("/blogposts/{post_id}", {
  params: {
    path: { post_id: "my-post" },
    query: { version: 2 },
  },
});


// To maintain code structure and modularity, we can define a module interface:

export async function getBlogPostById(args: ??) : Promise< ???> {

} 

For illustration purposes, here are some typings:


type Paths = "/a" | "/b" | "/c";

type PathToMethodMap = {
  "/a": {
    GET: (query: {search: string}) => {id: string; value: string}; 
  },
    "/b": {
    GET: (query: {search: string}) => {id: string; value: string}; 
  }
      "/c": {
    GET: (query: {search: string}) => {id: string; value: string}; 
    PATCH: (body: {id: string, value: string}) => {id: string; value: string}; 
  }
}


function getClient<T extends Paths>(path: T ) : PathToMethodMap[T] {

}

getClient("/a").GET({search: "hello"})
getClient("/c").PATCH({id: "a", value: "b"})

We can implement a function like this:

function patchC(...args: Parameters<PathToMethodMap["/c"]["PATCH"]>)
: ReturnType<PathToMethodMap["/c"]["PATCH"]>{

}

However, in practical scenarios, these typings tend to be complex and cumbersome.

Is it possible to achieve a typing like this?

function alternativePatchC(...args: Parameters<typeof getClient[WHEN CALLED WITH "/c"]["PATCH"]>) 
: ReturnType<typeof getClient[WHEN CALLED WITH "/c"]["PATCH"]>{
  
}

Answer №1

Not sure if this information will be beneficial, but achieving the same outcome without invoking the function is possible by utilizing ReturnType for a generic function. This approach can help in avoiding the need to actually call the function. For instance, you could implement it like so:

function getClient<T extends Paths>(path: T ) : PathToMethodMap[T]{};

// Function equivalent to your initial code snippet
function alternativePatchC(...args: Parameters<ReturnType<typeof getClient<"/c">>["PATCH"]>) 
: ReturnType<ReturnType<typeof getClient<"/c">>["PATCH"]>{};

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

Ways to adjust the properties within a type that are nested

I'm looking to modify a specific type in my code while retaining the other properties. Can anyone help? type Foo = { a: { b: { c: string[] ...rest } ...rest } ...rest } Is there a way to change the type of a.b.c without ...

How can parameters be implemented in Angular similar to NodeJs Express style?

Is there a way to implement a Parameter in Angular routes that resembles the NodeJs style? I have a route like **http://myhost.domain.com/signin**" and I want to pass an id for the signin request. Although I can achieve this using **http://myhost.doma ...

What is the correct version compatibility matrix for Expo, NPM, Node, React Native, and TypeScript?

Currently, I am in the process of setting up React Native with TypeScript. Here are the steps I followed: npx react-native init MyApp --template react-native-template-typescript I made sure to install TypeScript as well: npm install -g typescript ' ...

Tips for implementing dynamic properties in TypeScript modeling

Is there a way to avoid using ts-ignore when using object properties referenced as strings in TypeScript? For example, if I have something like: const myList = ['aaa', 'bbb', 'ccc']; const appContext = {}; for (let i=0; i< ...

Prisma designs a personalized function within the schema

In my mongo collection, there is a field named amount. My requirement is to have the amount automatically divided by 100 whenever it is requested. In Django, this can be achieved with a custom function within the model. Here's how I implemented it: cl ...

Accessing file uploads in Angular 2

<div class="fileUpload btn btn-primary"> <span>Select File</span> <input id="uploadBtn" type="file" class="upload" value="No File Chosen" #uploadBtn/> </div> <input id="uploadFile" placeholder="No File Selected" disable ...

How to assign a value to an array within a form in Angular 8

I'm facing an issue with my Angular 8 edit form that utilizes a form array. When I navigate to the page, the form array is not populated with values as expected. Can anyone help me identify and solve this problem? ngOnInit(): void { // Fetc ...

Issue arose following the update from Angular 5 to 6, impacting the VSTS build process

Upon upgrading from Angular 5 to 6, I successfully got it running locally. It builds and compiles with --prod. Integration into an .NET MVC application went smoothly. However, when the build on VSTS is triggered, a series of errors surface: node_modules&b ...

Using react-google-charts to create visually appealing dual-Y stacked bar charts

I am currently working on developing a bar chart with specific criteria in mind. My data follows the format: [month, region, totalSalesForCompanyA, totalSalesForCompanyB] I have successfully implemented the following charts: A dual-Y bar chart where mo ...

The Vue data retrieved from an API using onMounted() is not initially showing up in the DOM. However, it magically appears after I make changes to the template

Hello and thank you to those taking the time to read this. I am new to Vue, so I may be overlooking something obvious here, but after being stuck for several days, I am reaching out for help. In my SFC file, I have an onMounted function fetching data from ...

Issue with Angular 7: "Unspecified name attribute causing control not found"

As I delve into the creation of my initial Angular application, I find myself faced with a series of errors appearing in the development mode console: ERROR Error: "Cannot find control with unspecified name attribute" ERROR Error: "Cannot f ...

Why is my Angular promise unexpectedly landing in the error callback?

I am facing an issue with my Angular + Typescript client. I have developed a PHP API and need to send a post request to it. Upon receiving the request, the server fills the response body with the correct data (verified through server debugging). However, w ...

What is the best way to access automatically generated JavaScript variables in TypeScript?

I am currently facing an issue with integrating a Google login API in my React project and I need some help. The problem arises when the user already has an active session, rendering the API unnecessary. The Javascript solution provided is as follows: co ...

Insert information into a 3-tiered nested Angular FormArray within interconnected dropdown fields

After trying to retrieve data from an API call to populate a select form field, I encountered difficulties setting the value correctly using a FormArray. This led me to creating a FormArray with 3 nested levels in Angular, taking reference from this examp ...

Implementing child components rendering in a React application using TypeScript

Just a little background information: I am attempting to build a carousel with pagination using ReactJS. Here is the code snippet I currently have: interface HTMLCarouselT { children: Array<JSX.Element> size: number; } const HTMLCarousel = ({ch ...

Convert a Java library to JavaScript using JSweet and integrate it into an Angular project

Just recently, I embarked on my journey to learn TypeScript. To challenge my newfound knowledge, I was tasked with transpiling a Java library using JSweet in order to integrate it into an Angular project. This specific Java library is self-contained, consi ...

Show information in a table based on a unique identifier

I am working with some data that looks like this [ { date: '20 Apr', maths: [70, 80.5, 100], science: [25, 20.1, 30] }, { date: '21 Apr', maths: [64, 76, 80], science: [21, 25, 27] }, ]; My goal is to present ...

Turn off slider trace animation?

Check out the slider component in MUI here: https://mui.com/material-ui/react-slider/ I'm currently exploring how to disable the animation on the nub so it moves instantly to the new position. Any advice on how to achieve this? ...

Creating a type-safe dictionary for custom theme styles in Base Web

In my Next.js project, I decided to use the Base Web UI component framework. To customize the colors, I extended the Theme object following the guidelines provided at . Interestingly, the documentation refers to the theme type as ThemeT, but in practice, i ...

How can you display or list the props of a React component alongside its documentation on the same page using TypeDoc?

/** * Definition of properties for the Component */ export interface ComponentProps { /** * Name of something */ name: string, /** * Action that occurs when component is clicked */ onClick: () => void } /** * @category Componen ...