0
0
Typescriptprogramming~5 mins

Inferring types with infer keyword in Typescript

Choose your learning style9 modes available
Introduction

The infer keyword helps TypeScript guess a type inside a conditional type. It makes your types smarter by learning parts of other types automatically.

When you want to extract a type from a function's return type.
When you need to get the type of elements inside an array or tuple.
When you want to pull out the type of a promise's resolved value.
When creating reusable utility types that adapt to different inputs.
When you want to simplify complex type transformations by inferring parts.
Syntax
Typescript
type MyType<T> = T extends SomeType<infer U> ? U : never;

The infer keyword can only be used inside a conditional type.

The inferred type U is a new name you give to the part you want to extract.

Examples
This extracts the return type R from a function type T.
Typescript
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
This gets the type U of elements inside an array type T.
Typescript
type ElementType<T> = T extends (infer U)[] ? U : never;
This extracts the resolved value type V from a Promise type T.
Typescript
type PromiseValue<T> = T extends Promise<infer V> ? V : never;
Sample Program

This program defines a type GetReturnType that uses infer to find the return type of any function. Then it uses it to get the return type of greet, which is string. Finally, it assigns a string to message and prints it.

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

function greet(name: string): string {
  return `Hello, ${name}!`;
}

// Use the type to get the return type of greet
type GreetReturn = GetReturnType<typeof greet>;

// Example usage:
const message: GreetReturn = "Hello, friend!";
console.log(message);
OutputSuccess
Important Notes

If the type does not match the pattern, the conditional type returns never.

You can only use infer inside the extends part of a conditional type.

Using infer helps create flexible and reusable types that adapt to different inputs.

Summary

infer lets TypeScript guess a type inside conditional types.

It is useful to extract parts of complex types like function returns or array elements.

Use it to make your types smarter and more reusable.