sajad torkamani

In a nutshell

The infer keyword in TypeScript lets you capture and extract a type in the context of conditional type expressions. infer only works when used inside a conditional type expression.

Here’s an example use:

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

function addNums(a: number, b: number) {
  return a + b
}

function getGreeting() {
  return "Hi there"
}

type AddNumsReturnType = ExtractReturnType<typeof addNums>
type GetGreetingsReturnType = ExtractReturnType<typeof getGreeting>

See this example in the TypeScript playground.

Sources / relevant links

Tagged: TypeScript

Leave a comment

Your email address will not be published. Required fields are marked *