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 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
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' });
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' });
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, };
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'
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', };
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', };
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, };
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' });
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, };
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'
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', };
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', };
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, };
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' });
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, };
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'
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', };
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.

The main reasons for slow operation of DOM are the high cost of rearrangement and redrawing and low access efficiency. Optimization methods include: 1. Reduce the number of accesses and cache read values; 2. Batch read and write operations; 3. Merge and modify, use document fragments or hidden elements; 4. Avoid layout jitter and centrally handle read and write; 5. Use framework or requestAnimationFrame asynchronous update.
