Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 7, 2022 10:50 am GMT

How the TypeScript Record Type Works

TypeScript Records are a great way to ensure consistency when trying to implement more complex types of data. They enforce key values, and allow you to create custom interfaces for the values.

That sounds confusing, but let's see how it works in practice.

Utility Types

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

How Typescript Record Types Work

Suppose you have a data set like this:

const myData = {    "123-123-123" : { firstName: "John", lastName: "Doe" },    "124-124-124" : { firstName: "Sarah", lastName: "Doe" },    "125-125-125" : { firstName: "Jane", lastName: "Smith" }}

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> = {    "123-123-123" : { firstName: "John", lastName: "Doe" },    "124-124-124" : { firstName: "Sarah", lastName: "Doe" },    "125-125-125" : { firstName: "Jane", lastName: "Smith" }}

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 = {    "uk" : { firstName: "John", lastName: "Doe" },    "france" : { firstName: "Sarah", lastName: "Doe" },    "india" : { firstName: "Jane", lastName: "Smith" }}

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> = {    "uk" : { firstName: "John", lastName: "Doe" },    "france" : { firstName: "Sarah", lastName: "Doe" },    "india" : { firstName: "Jane", lastName: "Smith" }}

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.


Original Link: https://dev.to/smpnjn/how-the-typescript-record-type-works-1f5m

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To