TypeScript Utility Types: Enhancing Code Reusability
Shafayet Hossain
Posted on October 17, 2024
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
};
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'>;
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'>;
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,
};
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😉
Posted on October 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.