search
HomeWeb Front-endJS TutorialTypeScript 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.

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

</user>

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

</user>

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

</car>

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'

</config>

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

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

</user>

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> = {
  id: 1,
  name: 'Bob',
};

</user>

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

</fruit>

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

</user>

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

</car>

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'

</config>

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

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

</user>

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> = {
  id: 1,
  name: 'Bob',
};

</user>

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

</fruit>

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

</user>

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

</car>

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'

</config>

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

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

</user>

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!

Statement
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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor