What is the use of Infer Keyword in TypeScript ?
Last Updated :
29 Apr, 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>;
// ResultWithoutInfer is 'string' in this case
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>;
// ResultWithInfer is 'string' in this case
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.
Use Case: Template Literal Types
The infer keyword in TypeScript extends its capabilities beyond conditional types, allowing for dynamic extraction and manipulation of types within template literal types. By leveraging infer within template literal types, developers can create sophisticated type mappings and transformations, enhancing type safety and expressiveness in TypeScript.
Example: Utilizing infer within a template literal type to extract substrings from a given string literal type.
JavaScript
type ExtractWords<S extends string> = S extends `${infer Word}
${infer Rest}` ? [Word, ...ExtractWords<Rest>] : [S];
type MyString = "Hello TypeScript World";
// Extracting words from MyString
type Words = ExtractWords<MyString>;
Expected Behavior: The ExtractWords type recursively extracts individual words from the input string literal type S using infer, resulting in an array of words.
Advantages:
- Fine-Grained Type Manipulation: infer within template literal types allows for fine-grained manipulation of string literal types, enabling complex type transformations.
- Dynamic Typing: Developers can dynamically derive and assign types within template literal types, enhancing type inference and adaptability.
- Enhanced Readability: By utilizing template literal types with infer, code becomes more expressive and readable, facilitating understanding and maintenance.
Similar Reads
Explain when to use "declare" keyword in TypeScript In TypeScript, the âdeclareâ keyword is important in ambient declarations. These declarations allow us to integrate third-party JavaScript libraries seamlessly into our TypeScript codebase. Think of it as a bridge that connects TypeScript with existing JavaScript code. In this article, weâll explore
4 min read
What is the Function type in TypeScript ? TypeScript is a JavaScript-based programming language with a typed syntax. It provides improved tools of any size. It adds extra syntax to JavaScript. This helps in facilitating a stronger interaction between you and your editor. It also helps in catching the mistakes well in advance. It uses type
3 min read
What is Type Predicates in Typescript ? In this article, we are going to learn about the type predicates in Typescript. TypeScript is a statically typed programming language that provides many features to make your code more efficient and robust. Type predicates in TypeScript are functions that return a boolean value and are used to narro
3 min read
What is an unknown type and when to use it in TypeScript ? In Typescript, any value can be assigned to unknown, but without a type assertion, unknown can't be assigned to anything but itself and any. Similarly, no operations on an unknown are allowed without first asserting or restricting it down to a more precise type. Â similar to any, we can assign any va
3 min read
What does the mean of pipe (|) symbol in Typescript ? In Typescript, pipe(|) is referred to as a union type or "Or". it is also called union type in typescript. A value that can be any of numerous kinds is described by a union type. Each type is separated by a pipe (|), thus the number| string represents a value whose type can be a string or a number.
3 min read