Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure:

interface Res<R = any> {
    first?(): Promise<R>;
    second(arg: { response: R }): void;
}

However, I noticed that when creating a plain object based on this interface, the response type is not inferred correctly. Here's an example:

const entity: Res = {
    first: () => Promise.resolve({ name: 'Bob' }),
    second: (arg) => {
        console.log(arg.response) // currently inferred as "any", but should be "{ name: string }"
    }
}

Is it feasible to obtain the correct type for arg.response based on the return value of the first() method?

TS Playground

Answer №1

To achieve the desired behavior, you cannot rely solely on a variable; instead, you can leverage the inference behavior of functions:

interface Res<R = any> {
    first?(): Promise<R>;
    second(arg: { response: R }): void;
}

function createRes<T>(o: Res<T>) {
    return o
}
const entity = createRes({
    first: () => Promise.resolve({ name: 'Bob' }),
    second: (arg) => {
        console.log(arg.response)
    }
})


Playground Link

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

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Leveraging PapaParse for CSV file parsing in a React application with JavaScript

I am encountering an issue with reading a CSV file in the same directory as my React app using Javascript and Papaparse for parsing. Below is the code snippet: Papa.parse("./headlines.csv", { download: true, complete: function(results, f ...

Avoiding code execution by injections in Javascript/Jquery

Currently, I'm fetching JSON data for a .getJSON function in Jquery. To ensure the data's security, I am considering using .text (I believe this is the correct approach). The JSON has been successfully validated. Below is the script that I am cu ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

Flashing Screens with Ionic 2

I am currently dealing with a situation where my login page and homepage are involved. I have implemented native storage to set an item that helps in checking if the user is already logged in (either through Facebook or Google authentication). The logic fo ...

When a user clicks a button, modify a section of the URL and navigate to

I've been searching everywhere for a solution to this issue, but I just can't seem to find it. I'm hoping someone here can help me out. In a bilingual store, I need a way to redirect users to the same product on a different domain when they ...

Having difficulty in choosing and displaying the dropdown values

Below is the code snippet: WebElement pooldropdown=driver.findElement(By.xpath("/html/body/section/section[2]/div[1]/select")); Select sel = new Select(pooldropdown); List<WebElement> list = sel.getOptions(); System. ...

Error with Firebase authentication on a Next.js project using TypeScript

I recently started a personal project using Next.js, Typescript, and Firebase for authentication and database management. While working on a sign-in page with Google integration, I encountered an error labeled as auth/argument-error. According to the Fireb ...

The NVD3 chart embedded in a React application generates HTML elements that persist on the page indefinitely without fading away

In my React application, I integrated an NVD3 scatter chart. However, I have encountered an issue with the tooltip not disappearing when hovering over the chart: https://i.stack.imgur.com/6lLok.png After moving the cursor away from the chart, the tooltip ...

Enhancing nested structures in reducers

Currently, I am utilizing react, typescript, and redux to develop a basic application that helps me manage my ingredients. However, I am facing difficulties with my code implementation. Below is an excerpt of my code: In the file types.ts, I have declared ...

Retrieving information from Firebase using React

Is there a way to retrieve data from Firestore? import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore'; const firebaseConfig = { apiKey: "AIzaSyCNBAxjeKNoAPPjBV0 ...

Despite changes in the state they are set to, the InitialValues remain constant

I am facing an issue with a Semantic-UI modal that includes a redux-form as its content. The form is passed to the modal when it opens, and the form element has an initialValues prop mapped to state. <FormModal handl ...

update confirmed data from a record

I am facing a unique challenge, where I have an edit form that updates a record in a table. One of the fields, let's say username, needs to be unique. To validate this, I am using the jQuery validation plugin along with the remote method as shown belo ...

An array devoid of elements may still hold significance

I have a specific function structure as follows: public returnData(): { points: Array<{ x: number, y: number }>, pointsCount: Array<number> } { return { points: [{x: 0, y: 1},{x: 1, y: 2 }], pointsCount: [1, 2, 3, 4] } ...

When attempting to print a Rectangle on my webpage using JavaScript and taking user input, I encountered an error stating that 'str' is not defined

I'm trying to implement a feature where clicking on the "try it" button will prompt the user for the number of lines and then print that many lines in the form of a rectangle. However, when I run my code, nothing appears on the DOM and there is an err ...

Tips for preventing HTML ID clashes while integrating with the Document Object Model of external websites

When incorporating additional HTML elements into a webpage using Javascript or jQuery, along with external CSS declarations, it is important to avoid conflicts with existing IDs and class names already present on the page. This could lead to issues if ther ...

Command to update a document in AWS DynamoDB using the Document Client

While attempting to utilize the UpdateCommand feature within the AWS DynamoDB documentation, I encountered various challenges due to its lack of detailed explanation and difficulty in implementation. My aim was to employ the update command to seamlessly t ...

Is there a more efficient solution for incorporating undefined and null into a type apart from developing a custom generic function?

Often in programming, we encounter methods where one or more parameters can be null or undefined (sometimes both with derived types). This can result in long method signatures like this: doThing( user: User | undefined | null, thing: Thing | undefined ...

Modifying the background color of a div with ng-click functionality

Having trouble changing the background color of a div that is already styled with white for odd elements and grey for even elements. I'm not sure why it's not working in Jsfiddle. The div also has an ng-click attribute that I haven't include ...

Injecting resolve into Angular controller and encountering undefined value in logging operation

My setup involves the following: .state('posts', { url: '/posts/{id}', templateUrl: 'posts.html', controller: 'postsController as postsCtrl', resolve: { post: getSinglePostWrapper ...