๐Ÿš€ Using infer in TypeScript

1 min read โค๏ธ 0 ยท ๐Ÿ’ฌ 0
#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.


Originally published on DEV Community . Read the discussion and share your thoughts there.

โœฆ

ยฉ 2026

LinkedIn ๐• GitHub