TypeScript Record<K, T> Utility Type Explained

Learn how Record<K, T> creates an object type with specified keys and value types. Examples for dictionaries, lookup tables, and typed key-value stores.

Object Types

Detailed Explanation

Understanding Record<K, T>

Record<K, T> constructs an object type whose property keys are K and whose property values are T. It is the go-to utility type for dictionaries and lookup tables.

Syntax

type Record<K extends keyof any, T> = {
  [P in K]: T;
};

Basic Example

type Role = "admin" | "editor" | "viewer";

interface Permission {
  read: boolean;
  write: boolean;
  delete: boolean;
}

type RolePermissions = Record<Role, Permission>;
// Equivalent to:
// {
//   admin: Permission;
//   editor: Permission;
//   viewer: Permission;
// }

String Index Signatures vs Record

// These are equivalent:
type Dict1 = Record<string, number>;
type Dict2 = { [key: string]: number };

Record is more readable and composable, especially with union keys.

Practical Pattern: Feature Flags

type FeatureFlag = "darkMode" | "newDashboard" | "betaAPI";

const flags: Record<FeatureFlag, boolean> = {
  darkMode: true,
  newDashboard: false,
  betaAPI: true,
};
// TypeScript ensures all flags are present and are booleans

Practical Pattern: Status-Based Rendering

type Status = "loading" | "success" | "error";

const statusMessages: Record<Status, string> = {
  loading: "Please wait...",
  success: "Operation completed!",
  error: "Something went wrong.",
};

Use Case

Use Record<K, T> when you need typed dictionaries, lookup tables, configuration objects with known keys, or any map-like structure where both keys and values should be type-checked.

Try It — TypeScript Utility Types

Open full tool