2

I try to create a function that takes a function as argument and returns a function with the same signature. This looks like this:

function create<TCreator extends (...args: any) => any>(creator: TCreator) {
  return (...params: Parameters<TCreator>) => creator(params);
}

And I use it like this:

const created = create((a: string, b: string) => ({
  a,
  b
}));

When I look at the type of the created variable, the return type is any instead of { a: string, b: string}:

const created: (a: string, b: string) => any

Any idea how I could fix that?

1 Answer 1

2

TypeScript doesn't know that the input function type is in any way related to the function type being returned, so you'll not only have to capture the parameter types (which you have done correctly!), but also the return type, something like this:

function create<TCreator extends (...args: any[]) => any>(creator: TCreator) {
  return (...params: Parameters<TCreator>): ReturnType<TCreator> => creator(params);
}

Two adjustments:

  • change the ...args type from any -> any[]
  • specify the return type of the new function using ReturnType<TCreator> type (requires TypeScript 2.8 or later)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.