When I began using TypeScript last winter, I have grown from defaulting to using any for all types more complex than a string or number to now feeling comfortable with the usage of advanced built-in types and custom types. Add types to your JavaScript code by switching to TypeScript to write air-tight applications. This article will provide examples of using advanced types and also how to use them in a React application.

We will discuss the Record , Partial , Required , Pick and a custom Omit types.

Record

A very useful built-in type introduced by Typescript 2.1 is Record : it allows you to created a typed map and is great for creating composite interfaces. To type a variable as Record , you have to pass a string as a key and some type for its corresponding value. The simplest case is when you have a string as a value:

const SERVICES: Record<string, string> = {

doorToDoor: "delivery at door",

airDelivery: "flying in",

specialDelivery: "special delivery",

inStore: "in-store pickup",

};

This may appear trivial, but it provides easy typing in your everyday code. One of the popular cases when Record works in well is an interface for a business entity that you keep in a dictionary as key-value pairs. This model could represent a collection of contacts, events, user data, transportation requests, cinema tickets, and more. In the following example, we create a model for products that a user could add to her cart:

Type Record is used for a dictionary of products in a user cart.

You see how the editor autocompletion will help us to define a typed object and will mark the variable with an error because not all the required properties are defined: