Understanding the Record Type in TypeScript

Javascript Jeep🚙💨
3 min readAug 15, 2024

When working with TypeScript, defining object types is a common task. There are several ways to do this. Let's explore the usual methods for defining object types.

Usual Way of Defining an Object

In TypeScript, you might typically define the type of an object using an interface or an index signature. Here’s how you might do it:

Using an Index Signature:

type NumericObject = {
[key: string]: number;
};

Here, we define an object type where the keys are of type string and the values are of type number.

Using an Interface:

interface UserDetails {
id: number;
age: number;
}

const user: UserDetails = { id: 123 , age: 30 }; // OK

Here , we define the key can be either id or age . This way we can define the list of possible key’s and key’s values and its types.

Using the Record Type

The Record type is a built-in TypeScript utility type that lets you define an object with a fixed set of keys and values. The syntax is:

Record<KeyType, ValueType>
  • KeyType: The type of the keys (number, string, symbol and literals).

--

--