TypeScript Utility Types: A Complete Guide
Detailed Blog page Skeleton loader
TypeScript Utility Types: A Complete Guide

TL;DR: TypeScript utility types are prebuilt functions that transform existing types, making your code cleaner and easier to maintain. This article explains essential utility types with real-world examples, including how to update user profiles, manage configurations, and filter data securely.

Advanced TypeScript Utility Types

TypeScript is a cornerstone in modern web development, enabling developers to write safer and more maintainable code. By introducing static typing to JavaScript, TypeScript helps catch errors at compile time. According to the 2024 Stack Overflow Developer Survey, TypeScript places 5th in the most popular scripting technologies among developers.

TypeScript’s amazing features are the main reason behind its success. For example, utility types help developers simplify type manipulation and reduce boilerplate code. Utility types were introduced in TypeScript 2.1, and additional utility types have been added in every new release.

This article will discuss utility types in detail to help you master TypeScript.

Syncfusion JavaScript UI controls are the developers’ choice to build user-friendly web applications. You deserve them too.

Understanding TypeScript utility types

Utility types are predefined, generic types in TypeScript that make the transformation of existing types into new variant types possible. They can be thought of as type-level functions that take existing types as parameters and return new types based on certain rules of transformation.

This is particularly useful when working with interfaces, where modified variants of types already in existence are often required without actually needing to duplicate the type definitions.

Core utility types and their real-world applications

Core utility types and applications

Partial

The Partial<Type> utility type takes a type and makes all its properties optional. This utility type is particularly valuable when the type is nested, because it makes properties optional recursively.

For instance, let’s say you are creating a user profile update function. In this case, if the user does not want to update all the fields, you can just use the Partial type and only update the required fields. This is very convenient in forms and APIs where not all fields are required.

Refer to the following code example.

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

const updateUser = (user: Partial<User>) => {
  console.log(Updating user: ${user.name} );
};

updateUser({ name: 'Alice' });

Required

The Required<Type> utility type constructs a type with all properties of the provided type set to required. This is useful to ensure that all the properties are available before saving an object to the database.

For example, if Required is used for car registration, it will ensure that you don’t miss any necessary properties like brand, model, and mileage when creating or saving a new car record. This is highly critical in terms of data integrity.
Refer to the following code example.

interface Car {
  make: string;
  model: string;
  mileage?: number;
}

const myCar: Required<Car> = {
  make: 'Ford',
  model: 'Focus',
  mileage: 12000,
};

Readonly

The Readonly<Type> utility type creates a type where all properties are read-only. This is really useful in configuration management to protect the critical settings from unwanted changes. 

For example, when your app depends on specific API endpoints, they should not be subject to change in the course of its execution. Making them read-only guarantees that they will remain constant during the whole life cycle of the app.

Refer to the following code example.

interface Config {
  apiEndpoint: string;
}

const config: Readonly<Config> = { apiEndpoint: 'https://api.example.com' };

// config.apiEndpoint = 'https://another-url.com'; // Error: Cannot assign to 'apiEndpoint'

Pick<Type, Keys>

The Pick<Type, Keys> utility type constructs a type by picking a set of properties from an existing type. This is useful when you need to filter out essential information, such as the user’s name and email, to display in a dashboard or summary view. It helps to improve the security and clarity of the data.

Refer to the following code example.

interface User {
  id: number;
  name: string;
  email: string;
}

type UserSummary = Pick<User, 'name' | 'email'>;

const userSummary: UserSummary = {
  name: 'Alice',
  email: '[email protected]',
};

Omit<Type, Keys>

The Omit<Type, Keys> utility type constructs a type by excluding specific properties from an existing type.

For example, Omit will be useful if you want to share user data with some third party but without sensitive information, such as an email address. You could do this by defining a new type that would exclude those fields. Especially in APIs, you may want to watch what goes outside in your API responses.

See the next code example.

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

const userWithoutEmail: Omit<User, 'email'> = {
  id: 1,
  name: 'Bob',
};

Every property of the Syncfusion JavaScript controls is completely documented to make it easy to get started.

Record<Keys, Type>

The Record<Keys, Type> utility type creates an object type with specified keys and values, which is useful when dealing with structured mappings.

For example, in the context of inventory management systems, the Record type can be useful in making explicit mappings between items and quantities. With this type of structure, the inventory data can be easily accessed and modified while ensuring that all fruits expected are accounted for.

type Fruit = 'apple' | 'banana' | 'orange';
type Inventory = Record<Fruit, number>;

const inventory: Inventory = {
  apple: 10,
  banana: 5,
  orange: 0,
};

Exclude<Type, ExcludedUnion>

The Exclude<Type, ExcludedUnion> utility type constructs a type by excluding specific types from a union.

You can use Exclude when designing functions that should only accept certain primitive types (e.g., numbers or Booleans but not strings). This can prevent bugs where unexpected types might cause errors during execution.

Refer to the following code example.

type Primitive = string | number | boolean;

const value: Exclude<Primitive, string> = true; // Only allows number or boolean.

Extract<Type, Union>

The Extract<Type, Union> utility type constructs a type by extracting specific types from a union.

In scenarios where you need to process only numeric values from a mixed-type collection (like performing calculations), using Extract ensures that only numbers are passed through. This is useful in data processing pipelines where strict typing can prevent runtime errors.

Refer to the following code example.

type Primitive = string | number | boolean;

const value2: Extract<Primitive, number> = 42; // Only allows numbers.

NonNullable

The NonNullable<Type> utility type constructs a type by excluding null and undefined from the given type.

In apps where some values need to be defined at all times, such as usernames or product IDs, making them NonNullable will ensure that such key fields will never be null or undefined. It is useful during form validations and responses from APIs where missing values would likely cause problems.

Refer to the next code example.

type NullableString = string | null | undefined;

const value3: NonNullable<NullableString> = 'Hello'; // null and undefined are not allowed.

ReturnType

The ReturnType<Type> utility extracts the return type of a function.

When working with higher-order functions or callbacks returning complex objects, such as coordinates, using ReturnType simplifies defining the expected return types without needing to state them manually each time. This can speed up development by reducing mismatched types-related bugs.

type PointGenerator = () => { x: number; y: number };

const point: ReturnType<PointGenerator> = {
  x: 10,
  y: 20,
};

Parameters

The Parameters<Type> utility extracts the parameter types of a function as a tuple.

This allows easy extraction and reuse of the parameter types in situations where one wants to manipulate or validate function parameters dynamically, such as when writing wrappers around functions. It greatly increases code reusability and maintainability across your codebase by ensuring consistency of function signatures.

Refer to the following code example.

function createUser(name: string, age: number): User {
  return { name, age };
}

type CreateUserParams = Parameters<typeof createUser>;

To make it easy for developers to include Syncfusion JavaScript controls in their projects, we have shared some working ones.

Advanced use cases with combinations of utility types

Combining these utility types can gain you powerful results when developing an app with TypeScript. Let’s look at some scenarios where multiple utility types work together effectively.

Combining Partial and Required

You can create a type that requires certain fields while allowing others to be optional.

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

// Combining Partial and Required
type UpdateUser = Required<Pick<User, 'id'>> & Partial<Omit<User, 'id'>>;

const updateUserData: UpdateUser = { id: 1, name: 'Alice' }; // Valid

In this example, UpdateUser requires the id property while allowing name and email to be optional. This pattern is useful for updating records where the identifier must always be present.

Creating flexible API responses

You might want to define API responses that can have different shapes based on certain conditions.

interface ApiResponse<T> {
  data?: T;
  error?: string;
}

// Using Record with Omit for flexible responses
type UserResponse = ApiResponse<Pick<User, 'name' | 'email'>>;

const response1: UserResponse = { data: { name: 'Alice', email: '[email protected]' } };
const response2: UserResponse = { error: 'User not found' };

Here, ApiResponse allows you to create flexible response types for an API call. By using Pick, you ensure that only relevant user data is included in the response.

Combining Exclude and Extract for filtering types

You might encounter situations where you need to filter out specific types from a union based on certain criteria.

Refer to the following code example.

type ResponseTypes = 'success' | 'error' | 'loading';

// Extracting specific response types while excluding others
type NonLoadingResponses = Exclude<ResponseTypes, 'loading'>;

const handleResponse = (responseType: NonLoadingResponses) => {
    if (responseType === 'success') {
        console.log('Operation was successful!');
    } else if (responseType === 'error') {
        console.log('An error occurred.');
    }
};

handleResponse('success'); // Valid call
// handleResponse('loading'); // Error as loading is excluded

Here, the Exclude utility is used to create a type (NonLoadingResponses) that excludes loading from the original ResponseTypes union, allowing the handleResponse function to accept only success or error as valid inputs.

Best practices

Use only necessary

While utility types are incredibly powerful, overusing them can lead to complex and unreadable code. It’s essential to strike a balance between leveraging these utilities and maintaining code clarity.

Refer to the next code example.

type User = {
  id: number;
  name: string;
  email?: string;
};

// Overly complex type using multiple utilities.
type ComplexUser = Partial<Required<Pick<User, 'name' | 'email'>>>;

// This can be confusing and hard to maintain.
const user1: ComplexUser = { name: 'Alice' }; // Valid, but unclear intent

Maintain clarity

Ensure that the purpose of each utility use case is clear. Avoid nesting too many utilities together, as it can confuse the intended structure of your types.

Refer to the following code example.

type Product = {
  id: number;
  name: string;
  description?: string;
  price: number;
};

// Clear and understandable use of utility types.
type ProductPreview = Pick<Product, 'id' | 'name'>;

const preview: ProductPreview = {
  id: 101,
  name: 'Smartphone',
};

Performance considerations

While performance impacts are rare at runtime since TypeScript types disappear after compilation, complex types can slow down the TypeScript compiler, affecting development speed.

// A complex type that could impact performance if used excessively.
type DeeplyNestedType = {
  level1: {
    level2: {
      level3: {
        level4: {
          level5: string;
        };
      };
    };
  };
};

// Accessing deeply nested properties can lead to performance issues
const example: DeeplyNestedType = {
  level1: {
    level2: {
      level3: {
        level4: {
          level5: 'Hello',
        },
      },
    },
  },
};

console.log(example.level1.level2.level3.level4.level5); // Performance hit on deep access

Easily build real-time apps with Syncfusion’s high-performance, lightweight, modular, and responsive JavaScript UI components.

Conclusion

There is no doubt that TypeScript is one of the most popular languages among web developers. Utility types are one of the unique features in TypeScript that significantly improve the TypeScript development experience and code quality when used correctly. However, we should not use them for every scenario since there can be performance and code maintainability issues.

Related blogs

Be the first to get updates

Madhura Jayashanka

Meet the Author

Madhura Jayashanka

I am a software developer passionate about creating IT solutions that drive societal transformation. I am skilled in Angular, Next.JS, AWS, and project architecture designing.