Transform the return type of a function in Typescript

I am looking to alter a function by changing its return type. While I came across this method on TypeScript: How to wrap a function, changing its return type?, I am seeking a more versatile solution.

type Test = (
    a: string,
    b: string,
    c: number,
) => string | Promise<string>;

type Test2 = (
    a: string,
    b: string,
    c: number,
) => number | Promise<number>;

My desired outcome would be something like:

// CopyFunction(Function, Return)
type Test2 = CopyFunction(Test, number | Promise<number>);

Answer №1

To achieve your desired outcome, you can create a custom type that utilizes conditional types and tuples in the rest parameter:

type CustomFunction<TFunc, TResult> = TFunc extends (...args: infer Args) => any ? (...args: Args) => TResult : never    
type ExampleType = CopyFunction<Example, number | Promise<number>>;

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

Slice an interactive div

I am currently working on setting up a horizontal sliding div for a menu. The layout consists of a left DIV that remains visible at all times, and a sliding DIV that appears horizontally when the menu is activated. My HTML code looks like this. <div id ...

The specified type '(Person | undefined)[]' cannot be assigned to the type 'People'

Encountering a typescript error while trying to update the state from the reducer: The error states: Type '(Person | undefined)[]' is not assignable to type 'People' reducer.ts: export type Person = { id: string; name: string; ph ...

Creating a unique object by dynamically incorporating features from another object

I've recently implemented a tree structure in my UI using Material Tree, and it requires creating a new object to represent the tree. The initial object format is as follows: [ { name: 'Fruit', children: [ {name: 'Apple& ...

How to retrieve TypeScript object within a Bootstrap modal in Angular

Unable to make my modal access a JavaScript object in the controller to dynamically populate fields. Progress Made: Created a component displaying a list of "person" objects. Implemented a functionality to open a modal upon clicking a row in the list. ...

What's stopping me from using useState() to assign API data to an array?

I have a question regarding my app that makes use of the Movies API. I am making an API request and then passing the data to an array using the useState hook. Here is a snippet of my code: const App = () => { type MovieType = { rate: string, ...

Manipulating objects within arrays in Typescript/Angular with a focus on copying

I'm currently facing issues with filtering an array using an HTML input. Here is the code snippet in question: ngOnInit() { this.dtoService.setJsonResponse(); this.getPool(); } getPool() { this.json = this.dtoService.jsonResponse; ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

When an empty array is returned from a catch statement in an async/await method, TypeScript infers it as never

Function getData() returns a Promise<Output[]>. When used without a catch statement, the inferred data type is Output[]. However, adding a catch statement in front of the getData() method changes the inferred data type to Output[] | void. This sugge ...

Deciding the conditional type within an IDE while using an If statement

When dealing with a type that can have two formats based on the value of one of its keys, such as: type singleOrMultiValue = {isSingle: true, value: string} | {isSingle: false, set: Array<string>} I have found it useful in preventing errors like con ...

In D3 Hierarchy Typescript, every parent-child duo is assigned the same color

I recently came across an interesting example of the "D3 Collapsible Force Layout" on this website. I decided to tweak the input data a bit: const data = { "name": "directory", "children": [ {"name": "1st file", "children": [{"name": "1f 1st func ...

Differentiating functions in Typescript through method overloading by inferring the second argument's type based on the first argument's

Looking to implement method overloading in Typescript with stricter type checking for method invocation based on different arguments. I am encountering an error: 'props' is possibly 'undefined'. This is the code that is causing the e ...

Is it possible to simultaneously update two entities using a single endpoint?

In order to update data in two different entities with a @OneToOne relationship between UserEntity and DetailsEntity, I need to create a function in my service that interacts with the database. Here are the entity definitions: UserEntity @Entity() export ...

Mastering the art of utilizing async await efficiently

Currently, I am trying to save/update data in my Firestore document. I have successfully implemented this without any issues by using an async function. However, I must admit that I am not very familiar with async functions or promises. I have provided my ...

Encountering the error "Object potentially undefined" while attempting to activate Cloud Function during document creation

My goal is to automatically create a new authenticated user whenever a new document is added to the "users" collection. The necessary user details will be extracted from the fields "email" and "phone" in the new document. The challenge I am facing is that ...

What is the mechanism behind making a Promise appear synchronous when using a Proxy in JavaScript?

const handler: ProxyHandler<any> = { get: (target: Promise<any>, prop: string, receiver: any) => { return target.then((o) => { return o[prop].apply(o); }); }, }; return new Proxy(obj, handler) ...

Limit the parameter of a TypeScript method decorator based on the method's type

Is it possible to generically restrict the argument of a method decorator based on the type of the method it is applied to? I attempted to obtain the method's type that the decorator is applied to using TypedPropertyDescriptor<Method>. However, ...

A function that creates a new object with identical keys as the original input object

I am working on creating a function fn() that has the following specifications: It takes a single argument x which is an object with optional keys "a" and "b" (each field may be numeric for simplicity) The function should return a new object with the same ...

The eslint rule 'import/extensions' was not found in the definition

I'm encountering two errors across all TypeScript files in ESLint on VS Code: Not able to find definition for rule 'import/extensions'.eslint(import/extensions) Not able to find definition for rule 'import/no-extraneous-dependencies&apo ...

Receive the most recent information from Angular's service method

I offer a unique service. handler.ts import { Observable,of,Subject } from 'rxjs'; import { PlayerService } from "./../../core/services/player.service"; import { Injectable } from "@angular/core"; import { DeezerService } from "../services/deez ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...