Create mapped types using Record type

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet

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.