Skip to main content

Utility Types in TypeScript (Live Playground)

In this tutorial, we will explore utility types in TypeScript. Understanding how to use utility types will help you write more flexible and type-safe code.

Utility types are built-in generic types provided by TypeScript that can be used to perform common operations on types.

Partial<Type>

The Partial utility type creates a new type with all the properties of the original type set as optional:

TypeScript
interface Person {
name: string;
age: number;
}

type PartialPerson = Partial<Person>;

const partialPerson: PartialPerson = { name: 'John Doe' };
Live Playground, Try it Yourself

Readonly<Type>

The Readonly utility type creates a new type with all the properties of the original type set as readonly:

TypeScript
interface Person {
name: string;
age: number;
}

type ReadonlyPerson = Readonly<Person>;

const readonlyPerson: ReadonlyPerson = { name: 'John Doe', age: 30 };
readonlyPerson.age = 31; // Error: Cannot assign to 'age' because it is a read-only property
Live Playground, Try it Yourself

Pick<Type, Keys>

The Pick utility type creates a new type by picking a set of properties from the original type:

TypeScript
interface Person {
name: string;
age: number;
address: string;
}

type PersonNameAge = Pick<Person, 'name' | 'age'>;

const personNameAge: PersonNameAge = { name: 'John Doe', age: 30 };
Live Playground, Try it Yourself

Omit<Type, Keys>

The Omit utility type creates a new type by omitting a set of properties from the original type:

TypeScript
interface Person {
name: string;
age: number;
address: string;
}

type PersonWithoutAddress = Omit<Person, 'address'>;

const personWithoutAddress: PersonWithoutAddress = { name: 'John Doe', age: 30 };
Live Playground, Try it Yourself

Extract<Type, Union>

The Extract utility type creates a new type by extracting the types that are assignable to the specified union from the original type:

TypeScript
type ActionTypes = 'add' | 'update' | 'delete';
type OtherActions = 'add' | 'search';

type CommonActions = Extract<ActionTypes, OtherActions>; // "add"
Live Playground, Try it Yourself

Exclude<Type, Union>

The Exclude utility type creates a new type by excluding the types that are assignable to the specified union from the original type:

TypeScript
type ActionTypes = 'add' | 'update' | 'delete';
type OtherActions = 'add' | 'search';

type ExclusiveActions = Exclude<ActionTypes, OtherActions>; // "update" | "delete"
Live Playground, Try it Yourself

Conclusion

In this tutorial, we have explored utility types in TypeScript. Understanding how to use utility types effectively will enable you to create more flexible and type-safe code.