Record type is an advanced type of TS. Let's see its definition first:
Record 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.
Flexiable keys
It is usually used when require a dictionary-like object. For example:
const records: Record<number, string> = {
1: 'a',
2: 'b'
}
This is a very simple but useful usage scenario. Its property keys are number and its property values are string. In this scenario, records don't have fixed number of member, it's extenable, you can add as much number-string pair as you like:
const pair: Record<number, string> = {
1: 'a',
2: 'b',
3: 'c',
....
99: 'X'
}
No error would be report , of course.
Fixed keys
While the number of keys of Record type can also be strict, let demostrate it by create a type "gameName" and an interface "comment", then combine them to serve a Record type:
type gameName = 'Sekiro' | 'Cyberpunk2077' | 'GTA'
interface comment {
hours: number,
review: 'good' | 'bad'
}
const game: Record<name, comment> = {}
In this moment, if you code it in a qulified IDE, it will report an error on variable game saying:
Type '{}' is missing the following properties from type 'Record': Sekiro, Cyberpunk2077, GTA
Which shows that the keys of Record type game is No more, no less, no deviation
Let's complete the missing property
const game: Record<gameName, comment> = {
'Sekiro': {
hours: 200,
review: 'good'
},
'Cyberpunk2077': {
hours: 30,
review: 'bad'
},
'GTA': {
hours: 500,
review: 'good'
}
}
Now everything is perfect, but if we try to add an extra property "Metro":
const game: Record<gameName, comment> = {
'Sekiro': {
hours: 200,
review: 'good'
},
'Cyberpunk2077': {
hours: 30,
review: 'bad'
},
'GTA': {
hours: 500,
review: 'good'
},
'Metro': {
hours: 100,
review: 'good'
}
}
Record will immediately yell out:
Object literal may only specify known properties, and ''Metro'' does not exist in type 'Record'.
Source code
Here is the source code of Record type
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};
That is, each attribute in K ([P in K]) is converted to type T.
Top comments (0)