microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.9k stars 12.47k forks source link

Inferring function parameters from the return type #56311

Open kyscott18 opened 12 months ago

kyscott18 commented 12 months ago

🔍 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.

jcalz commented 12 months ago

essentially a duplicate of #49618

3rd commented 12 months ago

Spent a few hours trying to work around this without success, adding my use case:

// would love for this to work: function create<T>(fn: (root: T) => T): T {}

const example = create((root) => ({
  static: 10,
  computed: () => root.static + 5,
}));

example.computed() // 15