5 Common TypeScript Utility Types

5 Common TypeScript Utility Types

TypeScript has a world-class and powerful type system that is very expressive and easy to use. Additionally, TypeScript utility types help developers with type transformation and are available globally.

In this article, we review 5 common TypeScript utility types.

Omit<Type, Keys>

Omit constructs a new type by removing Keys from properties of Type.

interface User  {
name: string, 
address: string,
age: number,
tel: number, 
}

type basicUser = Omit<User, "age" | "address">

Pick<Type,Keys>

The Pick utility type creates a new type by picking the set of properties Keys, from Type.

interface User  {
name: string, 
address: string,
age: number,
phone: number, 
}

type basicUser = Pick<User, "name" | "tel">

Partial<Type>

Partial creates a new type by setting all properties of Type to optional.

type User  {
name: string, 
address: string,
age: number,
phone: number, 
}

type unauthenticatedUser = Partial<User>

Required<Type>

The Required utility type is the opposite of partial. It constructs a new type by setting the properties of Type to required.

type User  {
name: string, 
address: string,
age: number,
phone: number, 
}

type authenticatedUser = Required<User>

‍‍Readonly<Type>

The Readonly utility type creates a new type by setting properties of Type to readonly.

interface User  {
name: string, 
address: string,
age: number,
phone: number, 
}

type authenticatedUser = Readonly<User>

Summary

TypeScript has built-in utility types that developers should use to increase their code readability and maintainability.