[TS] Create Optional in TypeScript
When programming with TypeScript, it is often necessary to define types to represent data structures. For example, let’s assume we have a type called Article that matches the structure of a database table.
export type Article = {
title: string;
content: string;
author: string;
createdAt: Date;
updatedAt: Date;
deletedAt: Date | null;
};
When creating an Article, some fields, such as updatedAt and deletedAt, may not be required. In such cases, it is common to define a type specifically for creation operations:
export type ArticleCreateInput = {
title: string;
content: string;
author: string;
createdAt: Date;
updatedAt?: Date;
deletedAt?: Date | null;
};
While this approach works, it introduces redundancy. The definitions of ArticleCreateInput and Article contain significant overlap, increasing maintenance costs and reducing the readability and ease of modification of the code.
Optimizing Code with TypeScript Features
To solve this issue, we can simplify the code by leveraging TypeScript’s advanced type features. By defining a generic Optional type, we can dynamically make specific fields optional:
export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
How the Optional Type Works
Omit<T, K>: Removes fields K from type T.Pick<T, K>: Extracts fields K from type T.Partial<Pick<T, K>>: Makes the extracted fields K optional.- Finally, the results are merged using the intersection type
&.
Using this utility type, we can easily create the ArticleCreateInput type without redundant definitions:
export type ArticleCreateInput = Optional<Article, 'updatedAt' | 'deletedAt'>;
Benefits of Optimization
- Reduced Code Redundancy: Avoids repetitive type definitions and focuses only on the fields that need changes.
- Improved Maintainability: When the Article type changes, related types are automatically updated.
- Enhanced Readability: Clearly expresses differences in fields, making the code more intuitive.
Conclusion
By using TypeScript utility types, you can reduce code redundancy and improve maintainability. Defining a generic Optional type allows you to make specific fields optional without repeatedly defining types like ArticleCreateInput. Hopefully, this technique will help streamline your project development and increase efficiency!