infer keyword
- TypeScript course
- Intermediate
- Lesson 40/89
- 4 min
Learn to extract types with infer.
The infer keyword
infer declares a new type variable inside the extends clause of a conditional type. This variable captures a part of the matched type and can be used in the true branch of the conditional. This lets you extract a sub-type from within a type.
type SarmaliAc<T> =
T extends { deger: infer V } ? V : never;
type R = SarmaliAc<{ deger: string }>;
// R: stringWhere does infer work?
infer is only valid inside the extends clause of conditional types; it cannot appear elsewhere. The declared type variable is visible only in the true and false branches. This mechanism is the foundation for structural inferences like Promise value type, array element type, or function return type.
Practice Unwrap a wrapper
Write the conditional type SarmaliAc<T> as T extends { deger: infer V } ? V : never. Define type Sonuc as SarmaliAc<{ deger: string }>. Define variable a with type Sonuc and assign "merhaba". Print a with console.log.
Starter code
// SarmaliAc<T> koşullu türünü tanımla
// T { deger: V } kalıbına uyuyorsa V'yi çıkar, değilse never
// Sonuc türünü SarmaliAc<{ deger: string }> olarak tanımla
// a değişkenini Sonuc türünde tanımla, "merhaba" ata
// a'yı console.log ile yazdırSample solution
type SarmaliAc<T> = T extends { deger: infer V } ? V : never;
type Sonuc = SarmaliAc<{ deger: string }>;
const a: Sonuc = "merhaba";
console.log(a);Expected output
merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does SarmaliAc<{ deger: number }> produce below?
type SarmaliAc<T> = T extends { deger: infer V } ? V : never;
type R = SarmaliAc<{ deger: number }>;- any
- number Correct answer
- { deger: number }
- never
Explanation: When T matches the pattern { deger: infer V }, V becomes the type of the deger property, which is number, and the true branch returns V. never only happens on mismatch; any is never an inference result.
2 Declare a type variable with infer
type SarmaliAc<T> =
T extends { deger: ____ V } ? V : never;
type SarmaliAc<T> =
T extends { deger: infer V } ? V : never;
Explanation: To declare a type variable in the extends clause of a conditional type you use infer. type, let and const are for value/type declarations elsewhere; they cannot infer.
3 infer parts
| Term | Meaning |
|---|---|
infer V |
Inferred type variable |
{ deger: infer V } |
Match pattern |
? V |
True branch: the inferred type |
SarmaliAc<{ deger: string }> |
Usage example |