microsoft / microsoft/TypeScript
Ability to replace return type of function type
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
- replace return type
- parameters generic
Suggestion
I would like to be able to replace just the return type of a function with a utility type, like WithReturn<F, R>.
I'm not 100% sure this is needed, but it seems like using (...args: Parameters<F>) => R is not sufficient because any generics in F are lost.
Use Cases
My use case is a utility function that captures the arguments to a function to allow it to be called later.
Examples
export const defer = <F extends (...args: any) => any>(f: F) => ((
...args: Parameters<F>
) => ({
function: f,
args,
})) /* as any as F */;
const map = <T, R>(array: Array<T>, f: (i: T) => R) => array.map(f);
const deferredMap = defer(map);
let r = deferredMap([1], (i: number) => 2); // error now: Type 'unknown' is not assignable to type 'number'.(2345)
r.args; // error if defer returns F
Right now there's an error because the generics to map() are lost when using Parameters.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the generic-loss behavior in the linked TypeScript Playground, focusing on Parameters and the proposed WithReturn<F, R> behavior. Done means a utility can preserve the generic parameters of a function type while replacing only its return type, without changing JavaScript runtime output.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100