Home

Record Type in TypeScript

Monday, August 28th, 2023

0 views

The usual way to define a type of an object in TypeScript is using an object type:

or an index signature:

These are good ways to define object types.

But Record<K, V>, the third approach, has the benefit of being shorter and more readable. Let's see how to use it in your code.

1. Record type

Record<K, V> is a generic type that represents an object type which keys are K and values are V.

For example, Record<string, number> is an object type with string keys and number values:

Record<string, number> is permissive regarding the object structure, as long as the keys are strings and values are numbers:

But Record<string, number> throws a type error if the value of a prop is a string:

There are 2 simple rules to remember regarding the allowed types of the keys and values. In Record<K, V>:

  • ArrowAn icon representing an arrow
    the key type K is restricted to number, string, symbol, including their literals
  • ArrowAn icon representing an arrow
    but there is no restriction on the value type V

Let's see some valid record types:

Types like boolean, object, Function, etc. are not accepted as keys:

2. Record with union key

As seen above, Record<string, number> permits any key names in the object. But quite often you need to annotate objects with a fixed set of keys.

The record type accepts a union type as a key, which is useful to fixate the keys.

A union of string literals is a common way to define the key type:

For example, Record<'annual' | 'bonus', number> represents an object which can have only annual and bonus keys:

Using less than necessary or keys than aren't in the union is prohibited:

The record type with union keys is equivalent to the regular object type. The record type has the benefit of not repeating the value type (like the regular object does):

3. Record benefits

I prefer record type instead of index signature most of the time. Record syntax is shorter and more readable (altought it's also a matter of taste).

For example, the record parameter is a bit easier to grasp than the index signature parameter:

Compared to record type, the index signature doesn't accept literals or a union as key type:

4. Conclusion

Record<K, V> is an object type with key type K and value type V.

The key type K can be only number, string, or symbol, including their literals. On the value type V is no restriction.

To limit the keys to a specific set, you can use a union of string literals Record<'key1' | 'key2', V> as the key type.

Check also my post index signatures to learning more about object types.

How often do you use record type?

To delete below!