microsoft / microsoft/TypeScript

Inferring function parameters from the return type

Open
#56,311 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔍 Search Terms

"inferring parameters types", "infer input from output types"

✅ Viability Checklist
⭐ Suggestion

I would like to infer the types of the parameters of a function based on the return type. I have tried a few patterns and I don't think this is currently possible.

📃 Motivating Example
const inferReturnValuesAsKeys = <
  T extends (arg: keyof ReturnType<T> & string) => Record<string, number>,
>(
  t: T,
) => t;

/**
 * @todo arg should be typed as 'a' instead of 'string'
 */
inferReturnValuesAsKeys((arg) => ({ a: 5 }));
// ^?
💻 Use Cases
  1. What do you want to use this for?

Helpful for strict typings and intellisense.

  1. What shortcomings exist with current approaches?

None give a strict enough type.

  1. What workarounds are you using in the meantime?

I don't have the type safety that I want.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the motivating TypeScript example and review the linked Design Goals and existing inference behavior. Determine whether the compiler can infer the callback parameter as the return object's key while preserving JavaScript output and existing type-checking behavior; done means the example has the requested type and suitable tests cover it.

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
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.