DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

🚀 Using infer in TypeScript

Extracting a Type with infer 🔍

The infer keyword is used in conjunction with the extends keyword to extract a type from a generic parameter. By using infer, you can perform type inference on a nested type that depends on the type of the input parameter.

Example:

Extracting the Type of the First Element of an Array 🌟

type FirstElement<T> = T extends [infer First, ...any[]] ? First : never;

const arr = ["foo", 42, true];
type FirstType = FirstElement<typeof arr>; // inferred type: string
Enter fullscreen mode Exit fullscreen mode

Example:

Extracting the Return Type of a Callback Function 🎯

function map<T, U>(arr: T[], callback: (value: T) => U): U[] {
  const result: U[] = [];
  for (const element of arr) {
    result.push(callback(element));
  }
  return result;
}

type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;

const arr = ["foo", "bar", "baz"];
const result = map(arr, (str) => str.length);
type ResultType = ReturnType<typeof result[number]>; // inferred type: number
Enter fullscreen mode Exit fullscreen mode

Conclusion:

infer is a powerful feature of TypeScript generics that allows you to extract types from generic parameters and perform type inference on nested types. By using infer, you can write more expressive and reusable code that is less error-prone.

Top comments (0)