Prefer utility types over model changes in TypeScript

RMAG news

Generally, in software, a model is an abstraction or a way to represent a system, process, or object in the real world. Modeling is the process of creating these abstractions to facilitate understanding, analysis, and design of system.

TypeScript provides several utility types to facilitate common type transformations, these utilities are available globally and can be used to avoid changing the nature of a model definition. Some of these utilities aim developers to keep their models consistency and you must use them rather than creating a new model to represent the variants of an existing entity in your code base.

The Pick

You may use a Pick when you want to construct a “light version” of an existing model, for instance, you want to represent a summary of an user model:

interface User {
firstName: string;
lastName: string;
age: number;
dateOfBirth: string;
primaryEmail: string;
secondaryEmail: string;
}

type UserBasicInfo = Pick<User, “firstName” | “lastName”>;

const userBasicInfo: UserBasicInfo = {
firstName: “Jonas”,
lastName: “Resenes”,
};

The Omit

The Omit is in the same “family” as the Pick, prefer Omit over Pick when you are composing a new type with a consider number of fields from an existing model.

interface User {
firstName: string;
lastName: string;
age: number;
dateOfBirth: string;
primaryEmail: string;
secondaryEmail: string;
}

type UserPreview = Omit<User, “primaryEmail” | “secondaryEmail”>;

const userPreview: UserPreview = {
firstName: “Jonas”,
lastName: “Resenes”,
age: 36,
dateOfBirth: “08/21/1987”
};