How To Use Record Type In Typescript

Learn How to Use Record Utility Type in Typescript with Example

Today I was facing a problem where I wanted an object with a list of properties but with specific values like:

For example:

export type NBATeam = "Lakers" | "Celtics" | "Bulls" | "Warriors";

const nbaChampionships = {
    Lakers: 17,
    Celtics: 17,
    Bulls: 6,
    Warriors: 6
};

How can Typescript help me to do it?

Well, TypeScript provides a list of utility types that make it easier to handle various type-related operations; one of these utility types is the Record Type.

What is the Record Type?

The Record type allows us to construct an object type with specified keys and their corresponding values, so we can think of it as defining a map or a dictionary.

In deep is like:

type Record<K extends keyof any, T> = {
    [P in K]: T;
};

With Record, you're essentially telling TypeScript: "Hey, I want an object that has keys of type K, and every value under those keys should be of type T."

Learn more about Record Types

Example

Suppose we want to create a type representing the number of championships won by different NBA teams. We can define our team names and the corresponding type for the number of championships:

type NBATeam = "Lakers" | "Celtics" | "Bulls" | "Warriors";
type Championships = number;

Using the Record type, we can create a type that maps each NBA team to the number of championships they have won:

type ChampionshipRecord = Record<NBATeam, Championships>;

This tells TypeScript that our ChampionshipRecord type is an object where every key is an NBATeam, and every value is a Championships (number).

Now, let's use this type:

const nbaChampionships: ChampionshipRecord = {
    Lakers: 17,
    Celtics: 17,
    Bulls: 6,
    Warriors: 6
};

console.log(`Lakers have won ${nbaChampionships.Lakers} championships.`);

If you accidentally add a team that's not in our NBATeam type or provide a value for championships that isn't a number, it generates a compile-time error, ensuring our data stays consistent.

Recap

For me Record is so powerful and helps to be it ensures objects conform to a specific shape. It guarantees that the keys and values of an object are of a certain type, adding a level of predictability to our codebase.

I hope it helps you ;)