Better Programming

Advice for programmers.

Follow publication

TypeScript’s Record Type Explained

Everything you want to know about the Record utility type

Sunny Sun
Better Programming
Published in
4 min readJun 18, 2021
The word “Bold” in a book
Photo by Jeremy Bishop on Unsplash.

Record is one of the TypeScript utility types and has been available out-of-box since version 2.1.

I have to admit that I was a little confused when I read the official definition for the first time:

Record<Keys,Type>

Constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.” — TypeScript’s documentation

At face value, it says the Record type creates an object type that has properties of type Keys with corresponding values of type Type. But a similar feature can be achieved by using an index signature, so why would we want to use a Record type? What makes it different or useful?

Record Type vs. Index Signature

In TypeScript, we call the way of accessing an object property with square brackets an index signature. It is widely used for object types with unknown string keys and a specific value type. Here is an example:

type studentScore= { [name: string]: number };

The index signature example above can be expressed by a Record type as well:

type studentScore = Record<string, number>;

For this use case, the two type declarations are equivalent from a type-asserting perspective. But from the syntax perspective, the index signature is better. In the index signature approach, the name key expresses the intent more clearly, and another advantage is that it is shown in VisualCode IntelliSense.

Then why do we want to use a Record type?

Why is the Record type useful?

The benefit of Record types are conciseness. It is particularly useful when we want to limit the properties of an object. For example, we can use a union of string literals to specify the allowable keys for the Record type, as shown below:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Sunny Sun
Sunny Sun

Written by Sunny Sun

I am full stack developer. Love coding, learning, writing. Checkout my NestJS course: https://shorturl.at/cpJM7, visit my blog https://coffeethinkcode.com

Responses (1)

Write a response