What is the use of Infer Keyword in TypeScript ?
Last Updated :
15 Jan, 2024
The infer
keyword in TypeScript is primarily associated with conditional types and is used to capture and assign a type to a type parameter within the scope of a conditional type. It allows TypeScript to infer the type from a given expression and use it within the definition of a more complex type.
Use Case: Conditional Types
Example without infer
: This example shows without using infer
, we would need to explicitly specify the type of R
in the conditional type, losing the ability to dynamically capture the return type of exampleFunction
.
Javascript
type ExtractReturnTypeWithoutInfer<T> = T extends
(...args: any[]) => infer R ? R : never;
function exampleFunction(): string {
return "Hello, TypeScript!" ;
}
type ResultWithoutInfer =
ExtractReturnTypeWithoutInfer< typeof exampleFunction>;
|
Expected Behavior: The ResultWithoutInfer
type is inferred to be 'string'
because exampleFunction
returns a string.
Example with infer
: In this example, the infer
keyword allows TypeScript to automatically deduce and assign the return type of exampleFunction
to the type parameter R
. This makes the ExtractReturnTypeWithInfer
type more flexible and capable of adapting to different functions.
Javascript
type ExtractReturnTypeWithInfer<T> = T extends
(...args: any[]) => infer R ? R : never;
function exampleFunction(): string {
return "Hello, TypeScript!" ;
}
type ResultWithInfer =
ExtractReturnTypeWithInfer< typeof exampleFunction>;
|
Expected Behavior: Similar to the previous example, the ResultWithInfer
type is also inferred to be 'string'
because the infer
keyword allows TypeScript to automatically deduce and assign the return type of exampleFunction
to the type parameter R
.
Advantages:
- Dynamic Inference:
- The
infer
keyword enables TypeScript to dynamically infer and assign types based on the structure of the code.
- Conditional Typing:
infer
is commonly used in conditional types to capture and use types within the scope of the condition.
- Flexible Type Inference:
- It provides a level of flexibility by allowing TypeScript to infer types in a way that adapts to the actual structure and context of the code.
Share your thoughts in the comments
Please Login to comment...