Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

TypeScript Generics: From Basics to Advanced Patterns

Generics preserve relationships between types without duplicating implementations or giving up static checks through any. Their value is not merely the <T> syntax: a single implementation can handle several models while keeping precise information for callers. This guide moves from reusable functions to pagination contracts, validated API requests and inference control, with framework-independent examples.

Published Written by Reading time 9 min read
On this page Contents: quick navigation between sections

Type inference: one function, different data

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

const firstName = firstOrUndefined(["Ada", "Grace"]);
const firstScore = firstOrUndefined([10, 20]);
const empty = firstOrUndefined<number>([]);

console.log(firstName, firstScore, empty); // Ada 10 undefined

firstOrUndefined accepts a read-only array and returns an element of its exact inferred type. A string[] produces string | undefined; a number[] produces number | undefined. Callers do not need to supply a type argument explicitly each time. [1][2]

The explicit <number> on an empty array supplies information missing from its values. The return type includes undefined because index zero might not exist. readonly also accepts immutable array references without claiming deep immutability of their elements.

extends constraints and preserving the full model

interface Identifiable {
  id: string;
}

function findById<Item extends Identifiable>(
  items: readonly Item[],
  id: string,
): Item | undefined {
  return items.find((item) => item.id === id);
}

const products = [{ id: "p1", price: 49 }];
const product = findById(products, "p1");

console.log(product?.price); // 49

Searching by identifier only requires an id property of type string. Item extends Identifiable permits access to id inside the function while preserving the rest of the concrete model at the call site. The returned product still exposes price. [1]

A constraint is not the same as the return type: a function returning Item cannot manufacture an arbitrary Identifiable and claim it is Item, because that concrete model may require additional fields. A missing record is explicitly represented by undefined.

keyof and indexed access: type-safe field selection

function readField<Model extends object, Key extends keyof Model>(
  model: Model,
  key: Key,
): Model[Key] {
  return model[key];
}

const user = { id: 42, name: "Ada", active: true };
const name = readField(user, "name");
const active = readField(user, "active");

console.log(name.toUpperCase(), active); // ADA true

readField restricts Key to keys of Model and returns Model[Key], the exact value type associated with the selected key. Reading name yields string, while active yields boolean. Misspelled property names become compile-time errors. [3][4]

This is useful for configuring tables, forms and filters. A string supplied by a URL is not automatically a valid model key, however: validate it before access. A broad index signature can also weaken the compiler's ability to reject arbitrary names.

Generic interfaces and default type parameters

interface Page<Item, Cursor = string> {
  items: readonly Item[];
  nextCursor: Cursor | null;
}

interface Product {
  id: string;
  price: number;
}

const productPage: Page<Product> = {
  items: [{ id: "p1", price: 49 }],
  nextCursor: "page-2",
};

const numericPage: Page<Product, number> = {
  items: productPage.items,
  nextCursor: 2,
};

Page models a paginated response independently of its item type. Cursor defaults to string, so most consumers use Page<Product> while a numeric-cursor integration can use Page<Product, number>. In this example null represents the end of pagination. [1]

A default type parameter is not a JavaScript default value. It neither inserts a cursor property nor changes server behavior. Required type parameters cannot follow optional ones, and a default must satisfy its constraint when one is declared.

API requests: generics are not runtime validation

async function fetchValidated<Data>(
  url: string,
  parse: (value: unknown) => Data,
  signal?: AbortSignal,
): Promise<Data> {
  const response = await fetch(url, { signal });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  const payload: unknown = await response.json();

  return parse(payload);
}

interface Product {
  id: string;
  price: number;
}

function parseProduct(value: unknown): Product {
  if (
    typeof value !== "object" ||
    value === null ||
    !("id" in value) ||
    typeof value.id !== "string" ||
    value.id.trim().length === 0 ||
    !("price" in value) ||
    typeof value.price !== "number" ||
    !Number.isFinite(value.price) ||
    value.price < 0
  ) {
    throw new Error("Invalid product payload");
  }

  return { id: value.id, price: value.price };
}

function loadProduct(signal?: AbortSignal): Promise<Product> {
  return fetchValidated("/api/products/p1", parseProduct, signal);
}

Assigning a JSON payload to Product with an assertion or a generic type argument does not verify the server response. Generic type information is erased during compilation. Treat boundary data as unknown and convert it into a model through a parser. [5][6]

fetchValidated checks the HTTP status and passes the decoded JSON to parse. The example rejects invalid identifiers and negative or non-finite prices, inferring Product from parseProduct. AbortSignal allows the caller to cancel the request. Network, decoding and validation failures propagate to the caller, which owns retry and error-display policy. [10]

Generic classes: an in-memory repository

class MemoryRepository<Entity extends { id: string }> {
  private readonly records = new Map<string, Entity>();

  save(entity: Entity): void {
    this.records.set(entity.id, entity);
  }

  find(id: string): Entity | undefined {
    return this.records.get(id);
  }
}

interface Product {
  id: string;
  price: number;
}

const repository = new MemoryRepository<Product>();

repository.save({ id: "p1", price: 49 });

console.log(repository.find("p1")?.price); // 49

MemoryRepository stores records in a Map keyed by string and returns the exact Entity type. For a Product instance, save requires the complete product model and find returns Product or undefined. The constraint ensures that the implementation can read id. [1]

This repository suits temporary state or tests. It is not durable storage and retains object references, so later mutations remain visible. Generics improve the type contract without providing isolation, copying or synchronization by themselves.

const type parameters and NoInfer

function defineFields<const Fields extends readonly string[]>(fields: Fields) {
  return fields;
}

function selectDefault<Field extends string>(
  fields: readonly Field[],
  defaultField: NoInfer<Field>,
): Field {
  if (!fields.includes(defaultField)) {
    throw new Error("Unknown field");
  }

  return defaultField;
}

const fields = defineFields(["name", "price"]);
const selected = selectDefault(fields, "price");

console.log(selected); // price

The const Fields parameter with a readonly string[] constraint preserves the tuple of literal field names for an inline array instead of widening it to string[]. It cannot recover literal information already lost in a widened variable. Const type parameters are available from TypeScript 5.0. [7]

NoInfer<Field> prevents defaultField from contributing candidates to inference, so fields establishes the allowed set. price is valid, but color is rejected by the compiler. NoInfer is available from TypeScript 5.4. The runtime includes check remains useful if JavaScript or an untrusted source supplies the arguments. [8]

Conditional types and infer: modeling results

type ApiResult<Data> =
  | { status: "success"; data: Data }
  | { status: "error"; message: string };

type SuccessData<Result> = Result extends {
  status: "success";
  data: infer Data;
}
  ? Data
  : never;

interface Product {
  id: string;
  price: number;
}

type ProductResult = ApiResult<Product>;
type ProductData = SuccessData<ProductResult>;

function getPrice(result: ProductResult): number | undefined {
  if (result.status === "error") {
    return undefined;
  }

  return result.data.price;
}

const product: ProductData = { id: "p1", price: 49 };

console.log(getPrice({ status: "success", data: product })); // 49

ApiResult<Data> separates success with data from failure with a message. SuccessData uses infer to extract the data type from a matching branch. Because Result is a naked type parameter on the left of extends, the conditional distributes over the union; the error branch evaluates to never. [9]

At runtime, getPrice checks status before accessing price. Use this pattern when the result type truly depends on input data. Not every function needs a generic: if a type parameter does not connect positions in the contract, a simpler type is usually clearer. [2]

A useful generic expresses a real relationship rather than just an unknown type. When no such relationship needs to be preserved, a concrete type is often simpler. Constraints and defaults keep contracts readable; NoInfer helps when one argument should establish the permitted values. At system boundaries, actual data still needs validation. Combining these techniques delivers practical type safety without needless architectural complexity.

TypeScript Generics Type Inference Generic Constraints keyof Indexed Access Types NoInfer Conditional Types Runtime Validation Frontend Architecture

Frequently asked questions

What are generics in TypeScript?

Type parameters that allow a shared implementation to preserve relationships between input and output types. [1]

What is the difference between T and any?

T can retain a concrete type inferred at the call site, whereas any disables important type checks.

What does T extends U mean?

T must meet the constraint U but can contain additional information. [1]

Do generics validate API responses?

No. Runtime data must be checked, for example with a parser that accepts unknown. [5][6]

When should I use NoInfer?

When one argument should establish a type and another should be checked against it without contributing inference candidates. [8]

Sources and references

  1. TypeScript Handbook, Generics↩1↩2↩3↩4↩5↩6↩7↩8↩9
  2. TypeScript Handbook, More on Functions↩1↩2↩3
  3. TypeScript Handbook, Keyof Type Operator↩1↩2
  4. TypeScript Handbook, Indexed Access Types↩1↩2
  5. TypeScript Handbook, Everyday Types↩1↩2↩3
  6. TypeScript Handbook, Narrowing↩1↩2↩3
  7. TypeScript 5.0, const Type Parameters↩1↩2
  8. TypeScript 5.4, NoInfer↩1↩2↩3
  9. TypeScript Handbook, Conditional Types↩1↩2
  10. MDN, Using the Fetch API↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning