0
0
Typescriptprogramming~5 mins

Combining utility types in Typescript

Choose your learning style9 modes available
Introduction

Combining utility types helps you create new types by mixing existing ones. This makes your code flexible and easier to manage.

When you want to make some properties optional and others required in an object.
When you need to pick only certain properties from a type and also make some readonly.
When you want to exclude some properties from a type and then add new ones.
When you want to reuse parts of types but change how some properties behave.
Syntax
Typescript
type NewType = UtilityType1<UtilityType2<OriginalType>>;
You can nest utility types inside each other to combine their effects.
Common utility types include Partial, Pick, Omit, Readonly, Required, and Record.
Examples
This makes all properties of T optional and readonly.
Typescript
type PartialReadonly<T> = Readonly<Partial<T>>;
This picks only name and age properties from T and makes them required.
Typescript
type PickRequired<T> = Required<Pick<T, 'name' | 'age'>>;
This removes the password property from T and makes the rest readonly.
Typescript
type OmitAndReadonly<T> = Readonly<Omit<T, 'password'>>;
Sample Program

This program creates a new type SafeUser by removing the password property from User and making all remaining properties readonly. Then it creates a user object of this type and prints it.

Typescript
interface User {
  id: number;
  name: string;
  email?: string;
  password: string;
}

type SafeUser = Readonly<Omit<User, 'password'>>;

const user: SafeUser = {
  id: 1,
  name: 'Alice',
  email: 'alice@example.com'
};

// user.id = 2; // Error: Cannot assign to 'id' because it is a read-only property

console.log(user);
OutputSuccess
Important Notes

Combining utility types lets you build precise types without repeating code.

Remember that the order of utility types matters. For example, Readonly> is different from Partial>.

Use TypeScript's error messages to understand how your combined types behave.

Summary

Combining utility types helps create new, flexible types by mixing existing ones.

You can nest utility types like Partial, Readonly, Pick, and Omit.

This technique keeps your code clean and easy to update.