Record type allows you to create object types in a shorter way. Types for objects are normally defined in the below format:
type UserDetailType = {
name: string;
age: string;
};
type Users = {
[name: string]: UserDetailType
};
However, with the Record
utility you can construct the same type as follows
type UserDetailType = {
name: string;
age: string;
};
type Users = Record<string, UserDetailType>;
Kamran Ahmed: Here we have an AgesType, which is an object where the key is the name, with the type string, and the value for each of the keys is going to be number.
Then, we're creating an ages object with a bunch of different names, with the values set to each of the persons' age. Then, we are printing to the console all the ages that we have here.
There's a short form in TypeScript, which can be used to represent this kind of type. We can represent the same object type as type AgesType, Record.
First parameter is going to be the key of the object. In this case, it is going to be string because we have names. The second value is going to be the value of each of the keys, so number here.
Now, you can see that TypeScript is not complaining. We're able to get the same result as this type.
We can also restrict the keys here. Right now, we are being flexible with the names here, so it can be any string. I can add, let's say, Jennie Doe, with 50. TypeScript is still not complaining.
Let's say that we only want three names. I can put here type NamesType, so John Doe, Jane Doe, and Baby Doe. Now, I can use this NamesType instead of the string here.
Now, all these three properties are being allowed, but this property does not exist in the NamesType, so it is not being allowed. I can add here Jennie Doe as well, and the error goes away.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!