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

TypeScript Utility Types: A Complete Guide

Dec 08, 2024 am 03:41 AM

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.

1

2

3

4

5

6

7

8

9

10

11

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.

1

2

3

4

5

6

7

8

9

10

11

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.

1

2

3

4

5

6

7

8

9

10

11

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.

1

2

3

4

5

6

7

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.

1

2

3

4

5

6

7

8

9

10

11

12

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.

1

2

3

4

5

6

7

8

9

10

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.

1

2

3

4

5

6

7

8

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.

1

2

3

4

5

6

7

8

9

10

11

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.

1

2

3

4

5

6

7

8

9

10

11

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.

1

2

3

4

5

6

7

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.

1

2

3

4

5

6

7

8

9

10

11

12

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.

1

2

3

4

5

6

7

8

9

10

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.

1

2

3

4

5

6

7

8

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.

1

2

3

4

5

6

7

8

9

10

11

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.

1

2

3

4

5

6

7

8

9

10

11

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.

1

2

3

4

5

6

7

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.

1

2

3

4

5

6

7

8

9

10

11

12

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!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles