CodeBlanks Logo Icon CodeBlanks

Extracting from Promise

Learn the value type of a Promise with infer.

Extracting a value from a Promise

The pattern Promise<infer V> extracts the value type of a Promise as V. The pattern T extends Promise<infer V> ? V : T returns the value type when T is a Promise, or T itself otherwise. This is the basis of the Awaited utility type.

type Deger<T> =
  T extends Promise<infer V> ? V : T;
type R = Deger<Promise<number>>;
// R: number

Non-Promise types

When T is not a Promise, Deger<T> falls to the false branch and returns T as-is. For example Deger<number> gives number. This lets you write flexible helpers that work with both Promise and non-Promise types.

Practice Extract the Promise value type

Write the conditional type Deger<T> as T extends Promise<infer V> ? V : T. Define type Sonuc as Deger<Promise<number>>. Define variable a with type Sonuc and assign 42. Print a with console.log.

Starter code

index.ts
// Deger<T> koşullu türünü tanımla
// T bir Promise ise değer türünü çıkar, değilse T'yi döndür
// Sonuc türünü Deger<Promise<number>> olarak tanımla
// a değişkenini Sonuc türünde tanımla, 42 ata
// a'yı console.log ile yazdır

Sample solution

index.ts
type Deger<T> = T extends Promise<infer V> ? V : T;
type Sonuc = Deger<Promise<number>>;
const a: Sonuc = 42;
console.log(a);

Expected output

42

Questions and answers

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

1 What does Deger<Promise<string>> produce?

index.ts
type Deger<T> = T extends Promise<infer V> ? V : T;
type R = Deger<Promise<string>>;
  • Promise<string>
  • any
  • never
  • string Correct answer

Explanation: Since T is a Promise, the pattern matches and V becomes the Promise's value type, string. The true branch returns V. Promise<string> is the wrong branch; never and any are invalid here.

2 Extract the Promise value

Question
type Deger<T> =
  T extends Promise<____ V> ? V : T;
Answer
type Deger<T> =
  T extends Promise<infer V> ? V : T;

Explanation: To extract the Promise's value type you use the Promise<infer V> pattern. type, let and const are for value/type declarations; new is an expression operator; infer does the inference.

3 Promise infer parts

Term Meaning
Promise<infer V> Captures the Promise value type
? V True branch: the value type
: T False branch: T as-is
Deger<Promise<number>> Usage example

All lessons in Intermediate