CodeBlanks Logo Icon CodeBlanks

Summary - infer

Write your own Awaited and ElementOf types with infer.

Summary - infer

infer declares a type variable in the extends clause of conditional types, allowing you to extract a sub-type from within a type. Promise<infer V> gives the awaited value type; (infer E)[] gives the array element type. These patterns underpin Awaited and array helpers.

type Beklenen<T> =
  T extends Promise<infer V> ? V : T;
type Eleman<T> =
  T extends (infer E)[] ? E : never;

Practice Your own Awaited and Eleman types

Write the conditional type Beklenen<T> as T extends Promise<infer V> ? V : T. Write the conditional type Eleman<T> as T extends (infer E)[] ? E : never. Define type P as Beklenen<Promise<string>> and type E as Eleman<number[]>. Define a with type P as "tamam", and b with type E as 7. Print both on separate lines.

Starter code

index.ts
// Beklenen<T> koşullu türünü tanımla: Promise değerini çıkar
// Eleman<T> koşullu türünü tanımla: dizi elemanını çıkar
// P türünü Beklenen<Promise<string>> olarak tanımla
// E türünü Eleman<number[]> olarak tanımla
// a değişkenini P türünde tanımla, "tamam" ata
// b değişkenini E türünde tanımla, 7 ata
// a ve b'yi ayrı satırlarda yazdır

Sample solution

index.ts
type Beklenen<T> = T extends Promise<infer V> ? V : T;
type Eleman<T> = T extends (infer E)[] ? E : never;
type P = Beklenen<Promise<string>>;
type E = Eleman<number[]>;
const a: P = "tamam";
const b: E = 7;
console.log(a);
console.log(b);

Expected output

tamam
7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which pattern extracts a Promise's value type?

index.ts
type Beklenen<T> = T extends Promise<infer V> ? V : T;
  • T extends Promise<V> ? V : T
  • T extends infer Promise ? T : never
  • T extends Promise<infer V> ? V : T Correct answer
  • T extends (infer V)[] ? V : never

Explanation: The Promise<infer V> pattern extracts the Promise's value type as V. The second extracts an array element; the third leaves V undefined; the last is a syntax error.

2 Extract the array element

Question
type Eleman<T> =
  T extends (____ E)[] ? E : never;
Answer
type Eleman<T> =
  T extends (infer E)[] ? E : never;

Explanation: To extract the array element type you use the (infer E)[] pattern. type, let and new do not declare a type variable; only infer infers inside the extends clause of a conditional type.

3 Match the infer patterns

Term Meaning
Promise<infer V> Extracts the Promise value type
(infer E)[] Extracts the array element type
{ deger: infer V } Extracts an object property type
? V / ? E True branch: the inferred type

All lessons in Intermediate