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;
}
With the above interface, we can create 4 different interfaces:
- name, description
- name, description, id
- name, description, isMarkedFavorite
- name, description, id, isMarkedFavorite
These kind of scenarios often come when we use an interface for Payload and Response of an API. For example:
- Create folder would need only 2 properties: name and description
- 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">;
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;
}
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
Top comments (0)