DEV Community

Shelner
Shelner

Posted on

"Record" utility type in TypeScript

The Record Utility Type in TypeScript

TypeScript provides a rich set of utility types to help developers write cleaner and more robust code. One of the most useful and versatile is the Record type. In this article, I'll explore what Record is, when to use it, and how to use it effectively with real-world examples.

What is Record?

The Record type is TypeScript utility type that lets you define an object type with a specific set of keys and a consistent value type for all keys.

Syntax

Record<Keys, ValueType>
Enter fullscreen mode Exit fullscreen mode
  • Keys: The union of keys you want the object to have (must be a type that extends string | number | symbol).
  • ValueType: The type of the values associated with those keys.

Example

type UserRole = 'admin' | 'user' | 'guest';

const rolePermissions: Record<UserRole, string[]> = {
  admin: ['read', 'write', 'delete'],
  user: ['read', 'write'],
  guest: ['read']
};
Enter fullscreen mode Exit fullscreen mode
enum Status {
  New = 'new',
  InProgress = 'in_progress',
  Done = 'done'
}

const statusLabels: Record<Status, string> = {
  [Status.New]: 'New Task',
  [Status.InProgress]: 'Task In Progress',
  [Status.Done]: 'Completed Task'
};
Enter fullscreen mode Exit fullscreen mode
type CountryCode = 'US' | 'JP' | 'FR';

const countryNames: Record<CountryCode, string> = {
  US: 'United States',
  JP: 'Japan',
  FR: 'France'
};
Enter fullscreen mode Exit fullscreen mode
type Lang = 'en' | 'ja';
type Page = 'home' | 'about';

const translations: Record<Lang, Record<Page, string>> = {
  en: {
    home: 'Home',
    about: 'About Us'
  },
  ja: {
    home: 'ホーム',
    about: '私たちについて'
  }
};
Enter fullscreen mode Exit fullscreen mode
type Product = {
  name: string;
  price: number;
};

type ProductID = 'p1' | 'p2';

const productCatalog: Record<ProductID, Product> = {
  p1: { name: 'Keyboard', price: 99 },
  p2: { name: 'Mouse', price: 49 }
};
Enter fullscreen mode Exit fullscreen mode
type Features = 'darkMode' | 'betaAccess';
const featureFlags: Partial<Record<Features, boolean>> = {
  darkMode: true
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)