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; </t>
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
Now, let’s introduce the infer keyword into the mix:
type MyInferredType<t> = T extends SomeType<infer u> ? U : FalseType; </infer></t>
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 any> any> = T extends (...args: any[]) => infer R ? R : any; </t>
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' </typeof>
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 any> any> = T extends (...args: infer P) => any ? P : never; </t>
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] </typeof>
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>> = T extends Promise<infer u> ? U : never; </infer></t>
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 fetchdata>>; // FetchedDataType is inferred as 'string' </returntype></string>
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>> = T extends Array<infer u> ? U : never; </infer></t>
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' </myarray>
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:
It can only be used within conditional types.
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!

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
