TypeScript
/Intermediate
Record<Keys, Type>
Definition
A utility type that constructs an object type whose property keys are `Keys` and whose property values are `Type`. It maps a set of keys to a specific type.
Explain Like I'm New
It is a fast, incredibly readable way to type a Dictionary or Hash Map. Instead of writing out a complex Index Signature, you just say `Record<string, number>`, meaning 'This is an object where every key is a string, and every value is a number'.
Real World Example
Typing a theme configuration object: `const theme: Record<'dark' | 'light', ThemeColors>`. This forces the object to strictly contain exactly those two keys.
Common Use Cases
- •Dictionaries
- •Mapping strict enums/unions to specific values
Interactive Example
// 1. Generic Dictionary (Any string key allowed) type Scores = Record<string, number>; const myScores: Scores = { math: 95, science: 80 }; // 2. Strict Mapping (Highly Powerful!) type Role = "admin" | "editor" | "guest"; // We map every role to a boolean (e.g., 'canEdit') // TS FORCES you to define all 3 keys. const permissions: Record<Role, boolean> = { admin: true, editor: true, guest: false }; // ERROR: Type is missing the 'guest' property // const badPerms: Record<Role, boolean> = { admin: true, editor: true };
Interview Questions
basic
- What is the difference between `Record<string, number>` and `[key: string]: number`?
intermediate
- Can the `Keys` parameter be a union type?