# The Record Type

> Defining objects as dictionaries or maps.

Subject: TypeScript | Lesson 37 of 54 | 3 min read
Interactive lesson: https://codewithanimation.in/typescript/record-type
Previous: [Partial & Required](https://codewithanimation.in/typescript/partial-and-required.md) | Next: [Pick & Omit](https://codewithanimation.in/typescript/pick-and-omit.md)

## 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
};
```

## Common mistake: Undefined Values

A dangerous quirk of `Record<string, number>` is that TypeScript assumes *every possible string* is a valid key and returns a `number`.

If you access `myRecord["doesNotExist"]`, TypeScript thinks it's a `number`, but at runtime it will be `undefined`. To be safe, use `Record<string, number | undefined>` if the dictionary might be sparse.

## Tip: Under the Hood

`Record` is actually just a mapped type! `type Record<K extends keyof any, T> = { [P in K]: T; };`

## Try it: Try it

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

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/record-type

## Check yourself

### Question 1

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

- A. Record is strictly for arrays.
- B. There is no functional difference; they compile to the exact same type.
- C. Index signatures are faster at runtime.

Correct answer: B

Record is just syntax sugar (a utility type) that maps directly to an index signature. They behave identically.

- Why not A: Record is for objects.
- Why not C: Types don't exist at runtime.

## 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.
