TypeScript 7 cheatsheet

TypeScript 7: Types

9 common TypeScript 7 tasks.

Define an object type

Describe the shape of an object with an interface.

interface User {
  id: number;
  name: string;
  email?: string;
}

Define a union type

Allow a value to be one of several types.

type Status = "idle" | "loading" | "error";
type Id = string | number;

Make a literal read-only

Infer the narrowest literal types and make properties readonly.

const routes = ["/home", "/about"] as const;
type Route = (typeof routes)[number];

Check a value without widening it

Verify a value matches a type while keeping its precise inferred type.

const palette = {
  red: [255, 0, 0],
  green: "#00ff00",
} satisfies Record<string, string | number[]>;

Write a generic function

Keep the relationship between input and output types.

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

Constrain a generic

Require that a type parameter has certain properties.

function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

Get the keys of a type

Build a union of an object type's keys.

type UserKey = keyof User; // "id" | "name" | "email"

Get a type from a value

Derive a type from a runtime value so they can't drift apart.

const defaults = { retries: 3, verbose: false };
type Options = typeof defaults;

Get a function's return type

Extract the type a function returns; wrap it in Awaited for async functions.

type Result = Awaited<ReturnType<typeof fetchUser>>;

Was this page helpful?