Typescript: ArgumentType?

Created on 4 Aug 2018  路  5Comments  路  Source: microsoft/TypeScript

Similar to how TS has ReturnType, is it possible to have ArgumentType? Or an example of how to extract a function's arguments and specify a different return type?

Example, due to redux-pack changing this action to a promise

export function createMyPackActionWithArgs(arg1: string, arg2?: string) {
  return { type: MY_PACK_ACTION, promise: fetchMyData() };
}

This technically returns a Promise when in component but an Object when reducer.

Question

Most helpful comment

@MartinJohns what if you want to infer all the args? How would this done as a spread given it has to be dynamic

All 5 comments

Just look at how ReturnType is defined or at conditional types in general.

type FirstArgument<T extends Function> = T extends (arg: infer R) => any ? R : never;
function foo(n: number) { }
type FirstArgOfFoo = FirstArgument<typeof foo>;

@MartinJohns what if you want to infer all the args? How would this done as a spread given it has to be dynamic

Looks like this does what is needed, but is only supported in 3.0:

type ArgumentTypes<T> = T extends (...args: infer U) => infer R ? U : never;
type ReplaceReturnType<T, TNewReturn> = (...a: ArgumentTypes<T>) => TNewReturn;

@rsolomon, that's a bummer :( can't jump to 3.0 yet :(

馃コ A new Parameters type was added to TS recently. Perhaps we can close this issue now.
https://github.com/Microsoft/TypeScript/blob/fa74cef81e488c8e5bf790020620f0226118cb58/lib/lib.es5.d.ts#L1464

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chanon picture chanon  路  138Comments

yortus picture yortus  路  157Comments

blakeembrey picture blakeembrey  路  171Comments

tenry92 picture tenry92  路  146Comments

RyanCavanaugh picture RyanCavanaugh  路  205Comments