Home > Web Front-end > JS Tutorial > TypeScript Utility Types: A Complete Guide

TypeScript Utility Types: A Complete Guide

Barbara Streisand
Release: 2024-12-08 03:41:09
Original
560 people have browsed it

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.

TypeScript Utility Types: A Complete Guide

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.

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

TypeScript Utility Types: A Complete Guide

Partial

The Partial 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' });

Copy after login
Copy after login
Copy after login
Copy after login

Required

The Required 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 User {
  id: number;
  name: string;
  email?: string;
}

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

updateUser({ name: 'Alice' });

Copy after login
Copy after login
Copy after login
Copy after login

Readonly

The Readonly 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 Car {
  make: string;
  model: string;
  mileage?: number;
}

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

Copy after login
Copy after login
Copy after login

Pick

The Pick** 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 Config {
  apiEndpoint: string;
}

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

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

Copy after login
Copy after login
Copy after login

Omit

The Omit 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;
}

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

const userSummary: UserSummary = {
  name: 'Alice',
  email: 'alice@example.com',
};

Copy after login
Copy after login
Copy after login

Record

The Record 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.

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

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

Copy after login
Copy after login

Exclude

The Exclude** 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 Fruit = 'apple' | 'banana' | 'orange';
type Inventory = Record<Fruit, number>;

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

Copy after login
Copy after login

Extract

The Extract 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.

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

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

updateUser({ name: 'Alice' });

Copy after login
Copy after login
Copy after login
Copy after login

NonNullable

The NonNullable 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.

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

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

Copy after login
Copy after login
Copy after login

ReturnType

The ReturnType 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.

interface Config {
  apiEndpoint: string;
}

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

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

Copy after login
Copy after login
Copy after login

Parameters

The Parameters 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.

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

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

const userSummary: UserSummary = {
  name: 'Alice',
  email: 'alice@example.com',
};

Copy after login
Copy after login
Copy after login

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;
}

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

Copy after login
Copy after login

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.

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

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

Copy after login
Copy after login

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.

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

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

updateUser({ name: 'Alice' });

Copy after login
Copy after login
Copy after login
Copy after login

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.

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

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

Copy after login
Copy after login
Copy after login

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.

interface Config {
  apiEndpoint: string;
}

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

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

Copy after login
Copy after login
Copy after login

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.

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

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

const userSummary: UserSummary = {
  name: 'Alice',
  email: 'alice@example.com',
};

Copy after login
Copy after login
Copy after login

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

  • Top Linters for JavaScript and TypeScript: Simplifying Code Quality Management
  • 7 JavaScript Unit Test Frameworks Every Developer Should Know
  • Use of the Exclamation Mark in TypeScript
  • Understanding Conditional Types in TypeScript

The above is the detailed content of TypeScript Utility Types: A Complete Guide. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template