DEV Community

Cover image for TypeScript - Build Types from Interfaces
Ankit Tanna
Ankit Tanna

Posted on

TypeScript - Build Types from Interfaces

We definitely need to be more vigilant when creating interfaces and types in TypeScript. If we define loosely typed interface then it is no different from any.

for example:

interface Folder {
   id?: string;
   name: string;
   description: string;
   isMarkedFavorite?: boolean;
}
Enter fullscreen mode Exit fullscreen mode

With the above interface, we can create 4 different interfaces:

  1. name, description
  2. name, description, id
  3. name, description, isMarkedFavorite
  4. name, description, id, isMarkedFavorite

These kind of scenarios often come when we use an interface for Payload and Response of an API. For example:

  1. Create folder would need only 2 properties: name and description
  2. Once the folder is created, you would get id of the folder and also user's preferences like if the user has marked the folder as favorite or not

Typically for Payload and Response, the developer would typically use the same interface. Instead, we can use TypeScript's Pick and Omit utils to create new interfaces.

interface BaseFolder {
   id: string;
   name: string;
   description: string;
   isMarkedFavorite: boolean;
}

type FolderPayloadV1 = Omit<BaseFolder, "id" | "isMarkedFavorite">;
type FolderPayloadV2 = Pick<BaseFolder, "name" | "description">;
Enter fullscreen mode Exit fullscreen mode

You can also use Partial to make all the properties of BaseFolder optional.

interface BaseFolder {
   id: string;
   name: string;
   description: string;
   isMarkedFavorite: boolean;
}

type FolderPayloadV3 = Partial<BaseFolder>

// Equivalent would be
{
   id?: string;
   name?: string;
   description?: string;
   isMarkedFavorite?: boolean;
}
Enter fullscreen mode Exit fullscreen mode

As a developer, if we put enough time in designing interfaces then it shapes our development pattern as well. Type in TypeScript allows us to mitigate development bugs in many unseen ways. Like if the developers knew that the API is expected to return 4 properties and out of the for properties one of the property is expected to come from another API source, hence the developer can avoid unwanted bugs.

Happy Coding!

I run a small YouTube channel named EverydayJavaScript. My target is to reach 10000 subscribers by end of year. Please subscribe my channel.
Subscribe: https://www.youtube.com/EverydayJavaScript

Oldest comments (0)