What is the Record Type in TypeScript?
Firstly, let's talk about the Record feature in TypeScript.
You can find an explanation of the Record type at the following URL:
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type
The Record type maps one type to another by accepting two types.
For instance:
type RGBColors = Record<'red' | 'green' | 'blue', number>;
Here, the Record type maps the number type (the second argument) to the union of "red", "green", and "blue" (the first argument).
The result is:
type RGBColors = {
"red": number;
"green": number;
"blue": number;
}
Understanding the Record Type Implementation in TypeScript
You can examine the implementation of the Record type at the following URL:
https://github.com/microsoft/TypeScript/blob/5d8ef4bdcb8bdbd4307c74a07b01e3bdf6e04b6a/lib/lib.es5.d.ts#L1590
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};
The Record type accepts two arguments:
The first argument is K extends keyof any
, which corresponds to "string" | "number" | "symbol"
. Hence, the first argument can be of "string" | "number" | "symbol"
type.
The second argument, T
, is a generic argument. It can accept all types.
Now, let's take a look into the Record type.
The key is [P in K]
. The in
keyword is used to iterate over K
to map P
.
For example, when K
is "red" | "green" | "blue"
, [P in K]
generates keys that are "red" | "green" | "blue"
.
Let's revisit the RGBColors type from earlier:
type RGBColors = Record<'red' | 'green' | 'blue', number>;
// This is equivalent to the above RGBColors.
type RGBColors = {
"red": number;
"green": number;
"blue": number;
}
With this explanation, we should now have a better understanding of the Record type in TypeScript.
Top comments (0)