TypeScript by Example

Function Utility Types

Deriving function, constructor, and async payload types with ReturnType, Parameters, InstanceType, and Awaited.

Some utility types derive new types from real functions and classes, so you do not repeat a signature by hand.

ReturnType extracts a return type. Awaited unwraps promises.

function fetchUser(id: string): Promise<{ id: string; name: string }> {
  return Promise.resolve({ id, name: "Ada" });
}
 
type FetchUserReturn = ReturnType<typeof fetchUser>;
type ResolvedUser = Awaited<FetchUserReturn>;

Parameters extracts argument types as a tuple. InstanceType extracts the instance from a class constructor.

type FetchUserParams = Parameters<typeof fetchUser>;
// [id: string]
 
class Repository {
  constructor(private db: string) {}
  find(id: string): Promise<{ id: string }> {
    return Promise.resolve({ id });
  }
}
 
type RepoInstance = InstanceType<typeof Repository>;

In production

ReturnType<typeof fn> is useful for third-party or generated functions you cannot edit. Derive the type from the source of truth instead of maintaining a duplicate annotation that can drift.

Enjoyed this? Get more software craft delivered to your inbox.