Posts tagged "utility"

Typescript function parameter type

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;

Typescript ReturnType

Typescript includes several useful utility types to enhance the type declarations of your code-base.

The ReturnType function is one of my favorite ones, as it helps reduce type definition duplication.

Suppose you have the following function definition:

type IsInText = (
  text: string
) => (
  term: string,
  minCount: number,
  maxCount?: number,
  caseSensitive?: boolean
) => boolean

Now we want to write a function allTermsInText, that takes the function returned by isInText as an argument. It should be used like:

allTermsInText(["Typescript", "awesome"], isInText("Typescript is awesome!"))

Here is the definition without the utility type:

type AllTermsInText = (
  terms: string[],
  search: (
    term: string,
    minCount: number,
    maxCount?: number,
    caseSensitive?: boolean
  ) => boolean
) => boolean

And here the same function definition, but using ReturnType for the parameters:

let AllTermsInText = (terms: string[], search: ReturnType<IsInText>) => {
  return !terms.find(term => !search(term, 1))
}