The Record Type

Defining objects as dictionaries or maps.

TypeScript3 min readConcept 37 of 54

Key-Value Stores

The Record<Keys, Type> utility is used to define an object type whose property keys are Keys and whose property values are Type.

It is the cleanest way to define dictionaries, lookups, or hash maps in TypeScript.

Cleaner than Index Signatures

You can achieve the same result using an index signature like { [key: string]: number }.

However, Record<string, number> is much easier to read, quicker to write, and composes better when dealing with complex unions.

Syntax

typescript // 1. Generic dictionary type StringMap = Record<string, any>; // 2. Specific lookup map type Role = "admin" | "user" | "guest"; // TypeScript will force us to provide all 3 keys! const permissions: Record<Role, boolean> = { admin: true, user: false, guest: false };

Try it

Compare the Record<K, T> utility syntax against the raw index signature syntax it generates under the hood.

// 1. Using the Record utility
type MapA = Record<string, number>;

// 2. Using an Index Signature
type MapB = {[key: string]: number};

// They are functionally identical!
const scores: MapA = { Alice: 95 };
Syntax Sugar
Utility Type
Record<string, number>
Index Signature
{ [key: string]: number }
Under the hood
{ [P in K]: T }

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary difference between `Record<string, number>` and `{ [key: string]: number }`?

Remember this

  • Record<K, T> defines an object where all keys are type K and all values are type T.
  • It is functionally identical to an index signature {[k: string]: T}.
  • It is incredibly useful for mapping union types (like roles) to specific values.
  • Be careful when accessing arbitrary strings; they might be undefined at runtime despite what TS says.

Done with this concept?

Mark it complete to track your progress. No login needed.