Type System
TS infer Keyword
Using the infer Keyword
TypeScript infer keyword extracts types in conditional types for advanced logic.
Introduction to the infer Keyword
The infer keyword in TypeScript is used to extract types within conditional types. It allows developers to capture and utilize types in a way that can lead to more flexible and powerful type manipulations. This post will guide you through how infer works and its practical applications.
Basic Syntax of infer
The infer keyword is used in the context of conditional types. The basic syntax involves using infer
within a extends
clause. Here is an example of its syntax:
In this example, ReturnType
is a conditional type that checks if T
is a function type. If it is, infer R
captures the return type of the function, and R
is returned; otherwise, it defaults to any
.
Practical Example: Extracting Return Types
Let's see a practical example where the infer
keyword can be used to extract return types from function signatures:
In this example, the AddReturnType
will infer and extract the return type of the add
function, which is number
.
Using infer in Tuple Type Manipulation
The infer
keyword is particularly useful when working with tuple types. It can help in extracting the type of the first element of a tuple:
Here, First
is a type that uses infer
to extract the type of the first element in a tuple T
. For the example tuple [string, number, boolean]
, the extracted type is string
.
Advanced Use Case: Nested infer
Another advanced use of infer
is in nested scenarios where you might need to infer types at multiple levels:
In this case, Flatten
is used to strip away layers of arrays. The ElementType
will be number
because it infers through two levels of nested arrays.
Conclusion
The infer keyword in TypeScript is a powerful tool for type manipulation, especially when working with complex types. Its ability to extract types within conditional types makes it invaluable for developers looking to create more dynamic and reusable types. Practice using infer
in different scenarios to fully leverage its capabilities in your TypeScript projects.
Type System
- Previous
- keyof Operator
- Next
- Indexed Types