Back

Understanding infer in TypeScript

The `infer` keyword in TypeScript is used within conditional types to extract and name a type for later use. It is commonly used to unwrap or transform types.

With `infer`, you can dynamically capture parts of a type — like return values, tuple elements, or string segments — during type evaluation.

Extracting Return Types with infer

The classic use of `infer` is to extract the return type from a function. This avoids manually specifying it and ensures consistency.

type GetReturnType<T> =
    T extends (...args: any[]) => infer R ? R : never;
  
  type Example = GetReturnType<() => number>; // number

Converting kebab-case to camelCase

`infer` can dissect a string type at the hyphen (`-`) and apply `Capitalize` to convert it into camelCase, enabling transformations on literal string unions.

type ConvertType = 'primary-variant' | 'secondary-variant';
  type ToCamelCase<T extends string> =
    T extends `${infer First}-${infer Second}`
      ? `${First}${Capitalize<Second>}`
      : T;
  
  type Result = ToCamelCase<ConvertType>; 
  // 'primaryVariant' | 'secondaryVariant'

Handling Nested kebab-case Strings

Using recursive conditional types and `infer`, we can deeply convert multi-segment kebab-case strings into nested camelCase formats.

type ConvertType2 = 'primary-primaryt-variant' | 'test-test-test';
  
  type ToCamelRecursive<T extends string> =
    T extends `${infer First}-${infer Rest}`
      ? `${First}${Capitalize<ToCamelRecursive<Rest>>}`
      : T;
  
  type Result = ToCamelRecursive<ConvertType2>;
  // 'primaryPrimarytVariant' | 'testTestTest'

Reversing an Array Using infer

`infer` works with tuples, too! You can use recursion to reverse an array type entirely at compile time.

type ArrayReverse<T extends unknown[]> =
    T extends [infer First, ...infer Rest]
      ? [...ArrayReverse<Rest>, First]
      : T;
  
  type Reversed = ArrayReverse<[1, 2, 3]>;
  // [3, 2, 1]

Conclusion

`infer` unlocks advanced pattern-matching logic in TypeScript, allowing you to create highly flexible and reusable utility types.

It’s a core tool for any developer working with advanced type-level programming in TypeScript.

Back