0
0
Typescriptprogramming~5 mins

Record type in Typescript

Choose your learning style9 modes available
Introduction

The Record type helps you create an object with specific keys and values of a certain type. It keeps your data organized and safe.

When you want to map a set of known keys to values of the same type.
When you need a simple dictionary-like structure with fixed keys.
When you want to ensure all keys have values of a certain type.
When you want to replace an object type with many similar properties.
When you want to avoid repeating the same type for each property.
Syntax
Typescript
Record<Keys, Type>

Keys can be a union of string literals or string or number.

Type is the type of the values for each key.

Examples
This creates a type with keys 'math', 'english', and 'science', each holding a number.
Typescript
type Scores = Record<'math' | 'english' | 'science', number>;

const studentScores: Scores = {
  math: 90,
  english: 85,
  science: 92
};
This allows any string as a key, with string values, like a phone book.
Typescript
const phoneBook: Record<string, string> = {
  'Alice': '123-4567',
  'Bob': '987-6543'
};
Use Record to store flags with true/false values for any string keys.
Typescript
type Flags = Record<string, boolean>;

const featureFlags: Flags = {
  darkMode: true,
  betaUser: false
};
Sample Program

This program defines fruit colors using Record and prints each fruit with its color.

Typescript
type FruitColors = Record<'apple' | 'banana' | 'cherry', string>;

const colors: FruitColors = {
  apple: 'red',
  banana: 'yellow',
  cherry: 'dark red'
};

for (const fruit in colors) {
  console.log(`${fruit} is ${colors[fruit]}`);
}
OutputSuccess
Important Notes

Record keys must be unique and known if you use a union of string literals.

You can use string or number as keys for more flexible objects.

Record helps catch errors if you forget a key or use the wrong value type.

Summary

Record creates an object type with specific keys and value types.

It is useful for mapping fixed keys to values of the same type.

It helps keep your code safe and clear by enforcing types.