Typescript function parameter type

2019-10-02

A previous post mentioned the Typescript ReturnType utility type. It is really handy to retrieve the return type of a function.

But there is also a type to retrieve the parameter list of a function. Meet Parameters<T>.

const add = (first: number, second: number) => first + second;

const cache = <T extends (...args: any) => any>(func: T) => {
  const cacheObject = {};
  return (...args: Parameters<T>) => {
    const hashedArgs = JSON.stringify(args);
    if (cacheObject.hasOwnProperty(hashedArgs)) {
      return cacheObject[hashedArgs];
    } else {
      return (cacheObject[hashedArgs] = func(...args));
    }
  };
};

See the full example here.

The code can be found at lib/lib.es5.d.ts:

/**
 * Obtain the parameters of a function type in a tuple
 */
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;

Loading comments...