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:

  1. Fine-Grained Type Manipulation: infer within template literal types allows for fine-grained manipulation of string literal types, enabling complex type transformations.
  2. Dynamic Typing: Developers can dynamically derive and assign types within template literal types, enhancing type inference and adaptability.
  3. Enhanced Readability: By utilizing template literal types with infer, code becomes more expressive and readable, facilitating understanding and maintenance.


What is the use of Infer Keyword in TypeScript ?

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.

Table of Content

  • Use Case: Conditional Types
  • Use Case: Template Literal Types

Similar Reads

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....

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....