Skip to content
← Insights
Nov 14, 20264 min read

Make TypeScript remember which values belong together

Discriminated unions, generic constraints, and mapped types preserve information during a refactor. Executable examples show what the compiler checks and where runtime validation is still needed.

An open laptop showing linked geometric blocks, surrounded by a branching path, paired puzzle pieces, and a small shield.

A useful TypeScript type remembers which values belong together. That relationship is what lets a refactor expose a mistake before the code runs.

The features in this article are established language tools, not a claim about the newest compiler release. They address different places where information can be lost: a branch through possible states, a helper accepting several shapes, and a derived type that needs to follow its source object.

Put the state in the shape

A request can be loading, successful, or unsuccessful. Giving one object several optional fields leaves the caller to decide which combinations are valid. A discriminated union records the permitted combinations directly.

type RequestState =
  | { status: "loading" }
  | { status: "success"; value: string }
  | { status: "error"; message: string };

function describeRequest(state: RequestState): string {
  switch (state.status) {
    case "loading":
      return "Loading";
    case "success":
      return state.value;
    case "error":
      return state.message;
    default: {
      const unexpected: never = state;
      return unexpected;
    }
  }
}

The common status field tells the compiler which member is present inside each branch. In the success branch, the value field is available. In the loading branch, the type has no such field.

The narrowing handbook explains that relationship and the use of never for exhaustiveness. Here, adding another state without handling it makes the default assignment fail type checking. The application gets a concrete reminder to decide what that new state means for this function.

The runtime behaviour still comes from the switch statement. The type makes omissions visible during checking; it does not execute another hidden inspection of the value when JavaScript runs.

Preserve the connection in a helper

A generic helper is useful when its output type depends on its input. A property lookup gives a small example.

function readProperty<T, K extends keyof T>(
  object: T,
  property: K
): T[K] {
  return object[property];
}

const order = { id: "A17", total: 42 };
const total = readProperty(order, "total");

The type of total is number because the selected property is the total field of this object. The constraint also rejects a property name that the object does not have. The caller does not need to widen the result into every possible value type from the object.

The generics handbook describes this pattern of constraining one type parameter through another. The relationship is the reason for the generic. A helper that accepts a type parameter but never connects it to another value may be adding an annotation without expressing a useful constraint.

I would keep that distinction in mind when reviewing an abstraction. The question is what information survives the function call. If the caller loses a specific return type and has to assert it back into existence, the helper may have discarded the information it was supposed to preserve.

Derive related types from one definition

A change-handler type can follow the fields of a settings object. A mapped type describes that relationship without repeating each field's value type.

type Settings = {
  theme: "light" | "dark";
  pageSize: number;
};

type ChangeHandlers<T> = {
  [K in keyof T as `on${Capitalize<string & K>}`]?:
    (value: T[K]) => void;
};

const handlers: ChangeHandlers<Settings> = {
  onTheme: value => console.log(value),
  onPageSize: value => console.log(value)
};

The generated handler names follow the settings fields. The parameter of onTheme uses the theme value type; onPageSize receives a number. The mapped-types handbook explains this form of property-name remapping.

This is useful when the naming rule is genuinely part of the interface. It can be unnecessary complexity for a small object whose handlers have unrelated meanings. A derived type should make a real dependency visible, not force an incidental naming convention across the application.

The optional marker means an implementation can omit a handler. If every field requires a handler, that marker should be removed. The choice belongs to the behaviour the application expects, so the type should express it explicitly.

Keep the boundary with external data visible

TypeScript's basic-types documentation explains that type annotations are erased. A value received from a network request still needs runtime validation before the program can rely on its shape. An assertion that calls it RequestState does not perform that validation.

That boundary limits what the examples prove. The compiler can reason about a value once the program has a justified type for it. It cannot make an arbitrary response obey the application's type declaration.

These relationships make code easier to inspect because they put an assumption close to the operation that uses it. The next person changing a state or a field can then see which other code depends on that choice, with the compiler pointing to decisions that need attention.

TypeScriptSoftware development