CodePark/ questions / Utility types
START PRACTICINGPRACTICE
Frontend question · TypeScript › Utility types

A third-party library exports a function but not the types of its options or result. How do you get those types without copying them?

import { createClient } from "some-lib";

type ClientOptions = Parameters<typeof createClient>[0];
type Client = ReturnType<typeof createClient>;

// if createClient is async:
type ResolvedClient = Awaited<ReturnType<typeof createClient>>;

Get the function's type with typeof createClient, then apply utility types to it. You never copy the types by hand.

  • Parameters<F> gives the parameters as a tuple. So Parameters<typeof createClient>[0] is the type of the first argument, the options.
  • ReturnType<F> gives the return type.
  • If the function returns a promise, Awaited unwraps it to the resolved value.

This keeps your code in sync with the library. When the library changes its signature, your derived types update too.

One caveat: some functions are overloaded, meaning they have several call signatures. For these, ReturnType and Parameters use only the last overload signature.

  • typeof turns a runtime value, like a function, into its type.
  • Parameters<F>[0] gives the type of the first argument.
  • ReturnType<F> gives the result type, and Awaited unwraps a promise.
  • Derived types stay in sync when the library changes.
  • For overloaded functions, these utilities use only the last signature.