Home Web Front-end JS Tutorial Understanding the infer Keyword in TypeScript

Understanding the infer Keyword in TypeScript

Sep 28, 2024 am 06:17 AM

Understanding the infer Keyword in TypeScript

TypeScript, a statically-typed superset of JavaScript, has gained massive popularity in the tech community due to its ability to catch errors early and improve code readability. One of TypeScript’s powerful features is the infer keyword, which allows developers to write more expressive and dynamic types.

The Infer Keyword

Introduced in TypeScript 2.8, the infer keyword is used within conditional types to create temporary type variables. These type variables can then be used to infer types within a true or false branch of a conditional type. The infer keyword enables developers to write more dynamic and expressive types, as it allows TypeScript to determine a specific type based on the context in which it's used.

To better understand how infer works, let's take a look at the basic syntax of a conditional type:

type MyConditionalType<T> = T extends SomeType ? TrueType : FalseType;
Copy after login

In this example, T is a generic type parameter, and SomeType represents a type that T is being compared to. If T extends SomeType, the type of MyConditionalType will be TrueType. If not, it will be FalseType.

Now, let’s introduce the infer keyword into the mix:

type MyInferredType<T> = T extends SomeType<infer U> ? U : FalseType;
Copy after login

Here, we use the infer keyword to create a temporary type variable U within the true branch of the conditional type. If T extends SomeType, TypeScript will try to infer the type of U based on the type of T.

Examples

ReturnType

ReturnType is a utility type that extracts the return type of a function. It's a perfect example of how the infer keyword can be used to create dynamic types. Here's the definition of ReturnType:

type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;
Copy after login

In this definition, T is a function type that takes any number of arguments and returns any type. Using the infer keyword, we create a temporary type variable R to represent the return type of the function. If T is a function, TypeScript infers the return type and assigns it to R.

Let’s see ReturnType in action:

function greet(name: string): string {
  return `Hello, ${name}!`;
}
​
type GreetReturnType = ReturnType<typeof greet>; // GreetReturnType is inferred as 'string'
Copy after login

Here, ReturnType is used to infer the return type of the greet function, which is string.

Parameters

Another useful utility type that leverages the infer keyword is Parameters. This type extracts the parameter types of a function as a tuple. The definition of Parameters is as follows:

type Parameters<T extends (...args: any[]) => any> = T extends (...args: infer P) => any ? P : never;
Copy after login

In this example, we create a temporary type variable P to represent the parameter types of the function. If T is a function, TypeScript infers the parameter types and assigns them to P as a tuple.

Let’s look at an example using Parameters:

function add(a: number, b: number): number {
  return a + b;
}
​
type AddParameters = Parameters<typeof add>; // AddParameters is inferred as [number, number]
Copy after login

Here, Parameters is used to infer the parameter types of the add function, which is a tuple [number, number].

PromiseType

The PromiseType utility type can be used to extract the type that a Promise resolves to. This is particularly useful when dealing with asynchronous functions. Here's the definition of PromiseType:

type PromiseType<T extends Promise<any>> = T extends Promise<infer U> ? U : never;
Copy after login

In this example, we create a temporary type variable U to represent the type that the Promise resolves to. If T is a Promise, TypeScript infers the resolved type and assigns it to U. Here’s an example:

async function fetchData(): Promise<string> {
  return "Fetched data";
}
​
type FetchedDataType = PromiseType<ReturnType<typeof fetchData>>; // FetchedDataType is inferred as 'string'
Copy after login

In this case, PromiseType is used to infer the type that the fetchData function's promise resolves to, which is string.

UnboxArray

The UnboxArray utility type can be used to extract the type of the elements within an array. Here's the definition of UnboxArray:

type UnboxArray<T extends Array<any>> = T extends Array<infer U> ? U : never;
Copy after login

In this example, we create a temporary type variable U to represent the type of the elements within the array. If T is an array, TypeScript infers the element type and assigns it to U. For instance:

type MyArray = number[];

type ElementType = UnboxArray<MyArray>; // ElementType is inferred as 'number'
Copy after login

Here, UnboxArray is used to infer the type of elements within the MyArray type, which is number.

Limitations

While the infer keyword is incredibly powerful, it has some limitations:

  1. It can only be used within conditional types.

  2. It’s not always possible for TypeScript to infer the correct type, especially when dealing with complex or recursive types. In such cases, developers may need to provide additional type annotations or refactor their types to help TypeScript infer the correct type.

Conclusion

By understanding and leveraging the power of infer, you can create more flexible TypeScript projects. Start considering incorporating the infer keyword into your toolkit today.

If you found this helpful, please consider subscribing to my newsletter for more useful articles and tools about web development. Thanks for reading!

The above is the detailed content of Understanding the infer Keyword in TypeScript. 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
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

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.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

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.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles