Saturday, 9 April 2022

TypeScript Record Type

 Utility Types

A Record is a utility type — that means it is a type especially defined by TypeScript to help with a certain problem.

example you have a data set like this:

const myData = {
"adfsdfsd1" : { firstName: "Pranay", lastName: "Soni" },
"sddsf24" : { firstName: "Pranay1", lastName: "Soni1" },
"sdfsdf5" : { firstName: "Pranay2", lastName: "Soni2" }
}

Our data set has an ID for its key, which is of type string. All of the values have the same format — that is, they have a firstName and lastName.

For this data structure, a Record is the best utility type to use. We can define our data structure type as follows:

type User = {
firstName: string,
lastName: string
}
const myData:Record<string, User> = {
"123w" : { firstName: "Pranay1", lastName: "Soni1" },
"124s" : { firstName: "Pranay2", lastName: "Soni2" },
"125f" : { firstName: "Pranay3", lastName: "Soni3" },
}

A Record takes the form Record<K, T>, where K is the type of the key, and T is the type of the values.

Above, we defined a new type User for our values, and set our keys to type string.

Record Types and Union Types

Sometimes, we can have an object with a predefined set of possible keys. This is particularly true when calling from an API. For example:

const myData = {
"india" : { firstName: "Pranay1", lastName: "Soni1" },
"usa" : { firstName: "Pranay2", lastName: "Soni2" },
"japan" : { firstName: "Pranay3", lastName: "Soni3" },
}

Let’s presume that for our data set above, the key can only be three values: uk, france or india. In this case, we can define a type for User, and a union type for our key:

type User = {
firstName: string,
lastName: string
}
type Country = "uk" | "france" | "india";
const myData:Record<Country, User> = {
"india" : { firstName: "Pranay1", lastName: "Soni1" },
"usa" : { firstName: "Pranay2", lastName: "Soni2" },
"japan" : { firstName: "Pranay3", lastName: "Soni3" },
}

Using this method, we can enforce strict rules about the values the key is allowed to be, along with the type our values should conform to

No comments:

Post a Comment