TypeScript Course
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?

Flash Cards

Question

Difference between Record and Index Signatures?

Click to reveal answer
Answer

They compile to the exact same thing! However, `Record` is generally preferred for readability. Furthermore, `Record` allows you to pass specific String Unions (e.g., `'a' | 'b'`) as the keys, whereas inline Index Signatures do not allow unions.

Question

Can Keys be a union?

Click to reveal answer
Answer

Yes! This is the superpower of `Record`. If you do `Record<'admin' | 'user', boolean>`, TS forces the object to have EXACTLY an 'admin' key and a 'user' key. No more, no less.