In TypeScript, it is definitely possible to infer complex types

I've encountered a rather intriguing problem that I'm struggling to solve.

My goal is to develop a function that accepts an object of functions as input and returns an object with the same keys but a different return type, which depends on the values passed in as arguments.

For instance:

declare function add(a: number, b: number): number
declare function str(a: string, b: string): string

declare function createObject(obj)

const result = createObject({
   addFn: add,
   strFn: str
}) 

/*
   The desired TYPE for result should be:
   {
      addFn: [number, (a: number, b: number) => number],
      strFn: [string, (a: string, b: string) => string]
   }
*/

I believe this problem can be solved, but I am unsure about the approach. The closest solution I have come up with so far is shown below:

type GenericHashTable<T> = { [key in keyof T]: T[key] };

function createAPI<T extends { [k: string]: any }>(fetchers: T) {
  const obj: GenericHashTable<T> = fetchers;
  return obj;
}

However, this implementation does not allow me to change the return type effectively.

Answer №1

To achieve the desired outcome, it appears that utilizing the predefined ReturnType conditional type is all that is needed:

declare function add(a: number, b: number): number
declare function str(a: string, b: string): string

type CustomHashTable<T extends Record<keyof T, (...a: any[]) => any>> = { [key in keyof T]: [ReturnType<T[key]>, T[key]] };

declare function customizeAPI<T extends Record<keyof T, (...a: any[]) => any>>(operations: T): CustomHashTable<T>;

const finalResult = customizeAPI({
   sumFunction: add,
   concatFunction: str
}) 

// Equivalent to
const finalResult: {
    sumFunction: [number, (a: number, b: number) => number];
    concatFunction: [string, (a: string, b: string) => string];
}

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 observe redux action flow within a component

I am currently developing a React application structured with the following elements: redux typesafe-actions redux-observable My query is: How can I trigger a UI action when a specific redux action occurs? For instance, if we have these asynchronous ac ...

Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within th ...

React Component not displaying properly when used inside a map iteration

I am currently working on rendering multiple components using the .map method on an array with specific content. Although I can't find any errors in the console, the component is not appearing in the DOM as expected. I attempted to set subHeader to nu ...

Incorporating a custom transpiled file format into Typescript imports

I am trying to import a file format .xyz that does not have fixed types for all instances of the format: import { Comment, Article, User } from "./Blog.xyz" However, I keep getting this error message: TS2307: Cannot find module './Blog.xy ...

Is a JavaScript variable automatically global if not declared with var?

Here is the code snippet from one of my files: function refreshGridSuccess(responseText, entity) { oTable = $('#dataTable').dataTable({ "sScrollX": "100%", In a different file, I have the following code: $('#d ...

Tips for transferring state information from a client to a server component within Nextjs?

Currently, I am working on a project where I need to read and write data from a locally stored .xml file that contains multiple <user> tags. The technology stack includes TypeScript and NextJS. The project is divided into three main components sprea ...

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

Encountered an eas error during Android build process

When I try to execute the command "eas build --platform android" I encounter the following error message: "✖ Build failed ...

Generating step definitions files automatically in cucumber javascript - How is it done?

Is there a way to automatically create step definition files from feature files? I came across a solution for .Net - the plugin called specflow for Visual Studio (check out the "Generating Step Definitions" section here). Is there something similar avail ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...

Chaining asynchronous HTTP requests in Angular 2: A guide to stopping execution if one request fails

I am faced with a challenge of executing an array of HTTP requests in a specific order, where if any request fails, the subsequent ones should not be executed. Is there a way to achieve this requirement? What would be the recommended approach to hand ...

What is the best way to extract a mongoose model from an array that is nested within another mongoose model?

So I have two mongoose schemas: one for the model and another for the diagram. Model.ts import mongoose, {Schema} from 'mongoose'; import { Diagram } from "./index"; const modelSchema = new mongoose.Schema({ email: String, nam ...

Leveraging Angular 2 for incorporating jQuery-based JavaScript ajax functionality

It seems like I'm attempting to force a square peg into a round hole as I work with Angular2 and Typescript. I've created a Javascript module that serves as an API client library for the API I'm utilizing. This library simplifies tasks such ...

How can I properly include DefinitelyTyped TypeScript definition files in a .NET Core project?

Previously, under asp.net for .net framework, I utilized NuGet to incorporate TypeScript type definitions from third-party libraries (*.d.ts files) provided by DefinitelyTyped. However, with the shift to .NET Core, it seems that NuGet is no longer recommen ...

What is the reason for having a filled array containing data on currency exchange rates within an asynchronous function, while simultaneously having an empty array located outside of it? - React

After struggling with this programming issue for the past 5 days, I'm reaching out for help. The challenge I'm facing involves retrieving the rate of a specific currency between 1 and 50000 from an API. While I have successfully managed to obtai ...

Issue with displaying tab icons in Ionic 4

After updating the versions of Angular, Cordova, and Ionic, I started experiencing an issue with the tab icons displaying partially. Specifically, when my app loads with 4 tabs, only the first and third icons are visible. However, upon touching one of the ...

Error Encountered in Typescript Due to Undefined Environment Variable of Type "String"

When passing environment variables from my lambda-stack to my lambda function using the environment key, I encountered an error. Sending Variables: environment: { queueArn: sqsStack.sqsQueue.queueArn, queueUrl: sqsStack.sqsQueue.queueUrl, }, Error: T ...

How to submit a form in Angular2 without reloading the page

I have a straightforward form to transmit data to my component without refreshing the page. I've tried to override the submit function by using "return false," but it doesn't work as expected, and the page still refreshes. Here is the HTML: ...

Curious about where the data comes from? Look no further than TypeScript!

Can anyone help me figure out the source of my data in terms of class and method? Here's an example: EditValue(data) { /* my operations */ } I have several classes in my project that send data to this EditValue(data) method. Is there a method in T ...

Elevate the scope analysis for a function within the Jasmine framework

I have written a few functions within the app component. I am experiencing an issue with increasing coverage in the summary for these component methods. The test cases are functioning correctly, but some lines are not being accounted for in the coverage s ...