TypeScript 7 cheatsheet

TypeScript 7: Utility types and narrowing

8 common TypeScript 7 tasks.

Make all properties optional

Create a type where every property of User is optional, handy for update payloads.

type UserUpdate = Partial<User>;

Pick or omit properties

Create a type from a subset of another type's properties.

type UserSummary = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id">;

Type a dictionary

Describe an object with known key and value types.

type Scores = Record<string, number>;

Require or freeze properties

Make every property required, or read-only.

type Complete = Required<User>;
type Frozen = Readonly<User>;

Remove null and undefined

Exclude null and undefined from a type.

type Defined = NonNullable<string | null | undefined>; // string

Write a type guard

Tell the compiler how a check narrows a value.

function isString(value: unknown): value is string {
  return typeof value === "string";
}

Narrow an unknown value

Check the type before using a value of type unknown, such as parsed JSON.

function parse(input: unknown) {
  if (typeof input === "object" && input !== null && "id" in input) {
    return input.id;
  }
}

Check a switch handles every case

Make the compiler fail if a union member is not handled.

function label(status: Status): string {
  switch (status) {
    case "idle": return "Idle";
    case "loading": return "Loading";
    case "error": return "Error";
    default: {
      const unreachable: never = status;
      return unreachable;
    }
  }
}

Was this page helpful?