Generics and async types

7.0.2

Generics preserve a relationship between types without tying a function to one concrete type.

On this page

Reuse a function without losing types

The type parameter T connects the array element type to the return type. Include undefined when an empty array can have no result.

function first<T>(items: readonly T[]): T | undefined {
  return items[0];
}

const firstProduct = first(["Pen", "Notebook"]); // string | undefined

Describe an asynchronous result

An async function returns a Promise. When an API response enters the program, check its data shape at runtime before treating it as a typed value.

async function positivePrices(load: () => Promise<number[]>): Promise<number[]> {
  const prices = await load();
  return prices.filter(price => price > 0);
}

Official references