This article is part of the Series: Typescript utility types, in plain English
Record in a nutshell π₯
Our first utility type uses two arguments:Keys
and Type
.
Record<Keys, Type>
simply allows you to build an object type that has properties with keys Keys
of values Type
.
Sounds complex, but let me give you a very simple example:
type Television = Record<"sizeInInches", number>
/* is equal to
type Television = {
"sizeInInches": number
}
*/
let myBigTelevision:Television = {size: 23}
Example βοΈ
Pretty simple, but why and when would we use this?
Like any other utility type, its real power comes when you combine them, as we will see later.
However, Record<Keys, Type>
is useful to map a type to another type.
Let's say we are opening a television shop. Our Television
definition above needs more refining. On top of the size we want to know:
- if the TV is a smart TV or not,
- if it's an OLED or an LCD,
- if it has soundbars included,
- the definition
We redefine our Television
type.
type Television = {
brand: string,
model: string,
isSmart: boolean,
technology: "OLED" | "LCD", // We could use an `enum` here
hasSoundbars: boolean,
definition: "HD" | "FHD" | "2k" | "4k" | "8k",
}
In our store, we have already a system to create and record product ID numbers. We would like to map our existing product ID system to our Television
type such as:
const store = {
'product_id_1': { brand: 'Sumsang', model: '2000fe', isSmart: true, /* other properties */},
'product_id_2': /* another Television object */
/* more product */
}
In that case, we are mapping a product ID to an existing type: the perfect tool for the job is Record<Keys, Type>
:
type ProductID = string;
// βοΈ Here it's a string, but it could be a number, an object containing the quantity, etc.
type Store = Record<ProductID, Television>
// π Our new `Store` type for our store in a single line.
Conclusion βοΈ
Record<Keys, Type>
is the perfect tool to map an existing type to a new one.
In our example, we created a new mapped type in a single line of code.
Combined with other utility types, it becomes a very versatile tool.