Skip to content
jshacks.dev
TypeScript

Extract a type with infer

Use infer inside a conditional type to capture part of another type, such as an array's element or a function's first argument. TypeScript 5 and earlier.

1 min read
Summarize in AI

You want the element type of an array, or the first parameter of a function, as a named type. infer declares a variable the compiler fills in during the match.

infer.tsTypeScript
type ElementOf<T> = T extends readonly (infer U)[] ? U : never;
type FirstArg<F> = F extends (first: infer A, ...rest: any[]) => unknown ? A : never;

function greet(name: string, excited: boolean): string {
  return excited ? `Hi ${name}!` : `Hi ${name}`;
}

const name: FirstArg<typeof greet> = 'Ada'; // string
const first: ElementOf<string[]> = 'x'; // string

console.log(name, first);
Text
Ada x

In T extends readonly (infer U)[], U is not a name you declared elsewhere. The compiler matches T against the pattern and, if it fits, binds U to whatever sat in that position. ElementOf<string[]> is string. The built-in ReturnType and Parameters are written the same way. See inferring within conditional types.

infer can only appear in the extends clause of a conditional type. If the pattern does not match, you get the false branch, here never. When a type parameter shows up in several positions, TypeScript infers a union for covariant positions and an intersection for contravariant ones.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.