Utility types help make your code easier and faster to write by reusing common patterns. They save time and reduce mistakes when working with types.
0
0
Why utility types are needed in Typescript
Introduction
When you want to change some properties of an object type without rewriting the whole type.
When you need to create a new type based on an existing one but with some changes like making properties optional or readonly.
When you want to pick only some properties from a big type to use in a smaller part of your program.
When you want to combine or modify types quickly without repeating code.
When you want to ensure your code is safer by clearly defining how types should behave.
Syntax
Typescript
type NewType = UtilityType<ExistingType>;
Utility types are built-in TypeScript types that help transform other types.
You use them by passing an existing type inside angle brackets <>.
Examples
This makes all properties of
User read-only, so they cannot be changed.Typescript
type ReadonlyUser = Readonly<User>;
This makes all properties of
User optional, so you don't have to provide all of them.Typescript
type PartialUser = Partial<User>;
This creates a new type with only the
name property from User.Typescript
type UserName = Pick<User, 'name'>;Sample Program
This program shows how utility types like Readonly, Partial, and Pick change the shape of the User type to fit different needs.
Typescript
interface User {
id: number;
name: string;
email: string;
}
// Make all properties readonly
const user1: Readonly<User> = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
// user1.name = "Bob"; // Error: Cannot assign to 'name' because it is a read-only property.
// Make all properties optional
const user2: Partial<User> = {
name: "Bob"
};
// Pick only 'email' property
const userEmail: Pick<User, 'email'> = {
email: "charlie@example.com"
};
console.log(user1);
console.log(user2);
console.log(userEmail);OutputSuccess
Important Notes
Utility types help avoid repeating yourself by reusing existing types with small changes.
They improve code safety by clearly showing how types are modified.
Common utility types include Readonly, Partial, Pick, Omit, and more.
Summary
Utility types make working with types easier and faster.
They help create new types by changing existing ones without rewriting.
Using utility types leads to safer and cleaner code.