🛠️ Creating Custom Utility Types
TypeScript lets you create your own utility types using features like generics, mapped types, and conditional types.
This is useful when the same type transformation is needed in multiple places.
🔹 Example
Suppose you want to make only specific properties optional.
type User = {
name: string;
age: number;
email: string;
};
type Optional<T, K extends keyof T> = {
[P in K]?: T[P];
} & Omit<T, K>;
type UserUpdate = Optional<User, "name" | "age">;
const update: UserUpdate = {
email: "bhaskar@example.com"
};Here, name and age are optional, while email remains required.
type UserUpdate = {
name?: string;
age?: number;
email: string;
};💡 Why Create Custom Utility Types?
Custom utilities are useful when built-in utilities like Partial, Pick, or Omit don't exactly match your requirement.
Remember: Custom utility types let you create reusable type transformations for your application's specific needs.