DEV Community

Cover image for TypeScript Utility Types: Enhancing Code Reusability
Shafayet Hossain
Shafayet Hossain

Posted on

TypeScript Utility Types: Enhancing Code Reusability

TypeScript offers built-in utility types that allow developers to transform and reuse types effectively, making your code more flexible and DRY. In this article, we’ll explore key utility types like Partial, Pick, Omit, and Record to help you take your TypeScript skills to the next level.

Partial<T>: Making All Properties Optional
The Partial utility type converts all properties of a type to optional, which is helpful when dealing with object updates.

interface User {
  name: string;
  age: number;
}

const updateUser = (user: Partial<User>) => {
  // Now we can update only the properties we want
};
Enter fullscreen mode Exit fullscreen mode

Pick<T, K>: Selecting Specific Properties
Pick allows you to create a new type by selecting a subset of properties from an existing type.

type UserDetails = Pick<User, 'name'>;
Enter fullscreen mode Exit fullscreen mode

Omit<T, K>: Excluding Properties
Opposite of Pick, the Omit type excludes specific properties, which can be useful when you need a type with a few fields removed.

type UserWithoutAge = Omit<User, 'age'>;
Enter fullscreen mode Exit fullscreen mode

Record<K, T>: Defining an Object with Key-Value Pairs
Record allows you to define an object type where the keys are of a specific type and all values share the same type.

type UserRoles = Record<string, boolean>;

const roles: UserRoles = {
  admin: true,
  user: false,
};
Enter fullscreen mode Exit fullscreen mode

Conclusion
Utility types in TypeScript provide powerful tools to manipulate and reuse types effectively, making your code more modular and reusable. Mastering these utilities helps you write cleaner, more maintainable applications.


Thanks for reading! Let me know your thoughts on how you use utility types in your projects.
My website:https://shafayet.zya.me


A meme for you😉

Image description


Top comments (0)