The infer keyword helps TypeScript guess a type inside a conditional type. It makes your types smarter by learning parts of other types automatically.
Inferring types with infer keyword in Typescript
type MyType<T> = T extends SomeType<infer U> ? U : never;The infer keyword can only be used inside a conditional type.
The inferred type U is a new name you give to the part you want to extract.
R from a function type T.type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;U of elements inside an array type T.type ElementType<T> = T extends (infer U)[] ? U : never;V from a Promise type T.type PromiseValue<T> = T extends Promise<infer V> ? V : never;
This program defines a type GetReturnType that uses infer to find the return type of any function. Then it uses it to get the return type of greet, which is string. Finally, it assigns a string to message and prints it.
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never; function greet(name: string): string { return `Hello, ${name}!`; } // Use the type to get the return type of greet type GreetReturn = GetReturnType<typeof greet>; // Example usage: const message: GreetReturn = "Hello, friend!"; console.log(message);
If the type does not match the pattern, the conditional type returns never.
You can only use infer inside the extends part of a conditional type.
Using infer helps create flexible and reusable types that adapt to different inputs.
infer lets TypeScript guess a type inside conditional types.
It is useful to extract parts of complex types like function returns or array elements.
Use it to make your types smarter and more reusable.
Practice
infer keyword do in TypeScript conditional types?Solution
Step 1: Understand the role of
Theinferinferkeyword is used inside conditional types to let TypeScript guess a type variable from a given type.Step 2: Identify what
It extracts parts of complex types, like the return type of a function or the element type of an array.inferextractsFinal Answer:
It allows TypeScript to guess and extract a type inside a conditional type. -> Option BQuick Check:
inferextracts types = A [OK]
- Thinking infer declares variables in functions
- Confusing infer with interface creation
- Assuming infer imports types
F using infer?Solution
Step 1: Analyze the conditional type structure
The correct syntax usesF extends (...args: any[]) => infer Rto extract the return typeR.Step 2: Check each option for correct infer usage
type ReturnType<F> = F extends (...args: any[]) => infer R ? R : never; correctly placesinfer Rafter the arrow function parameters and before the return type.Final Answer:
type ReturnType<F> = F extends (...args: any[]) => infer R ? R : never; -> Option AQuick Check:
Correct infer syntax for return type = A [OK]
infer R right after function args in extends [OK]- Placing infer outside the extends clause
- Using infer on the wrong part of the function type
- Confusing parameter inference with return type inference
ElementType?
type ElementType<T> = T extends (infer U)[] ? U : T; type Result = ElementType;
Solution
Step 1: Understand the conditional type with infer
The type checks ifTextends an array of some typeU. If yes, it extractsU.Step 2: Apply the type to
Sincestring[]string[]extends(infer U)[],Uisstring. So,ElementType<string[]>isstring.Final Answer:
string -> Option AQuick Check:
Extracted element type = string [OK]
- Confusing the whole array type with element type
- Assuming infer returns the original type
- Ignoring the conditional fallback
type ArgType<T> = T extends (arg: infer A) => void ? A : never; type Test = ArgType<() => number>;
Solution
Step 1: Analyze the function type used
The function type() => numberhas no arguments.Step 2: Understand infer behavior with no matching argument
The conditional type tries to infer argumentA, but since there is no argument, the condition fails and returnsnever.Final Answer:
The function type has no arguments, so infer fails and returns never. -> Option CQuick Check:
Infer fails with no matching argument = C [OK]
- Assuming infer always succeeds
- Misplacing infer keyword syntax
- Confusing argument and return type inference
Flatten<T> that extracts the element type from nested arrays using infer. For example, Flatten<number[][]> should be number[]. Which of the following correctly implements this?Solution
Step 1: Understand the goal of Flatten
We want to recursively unwrap nested arrays until we reach a non-array element, then wrap it back as a single array.Step 2: Analyze type Flatten<T> = T extends (infer U)[] ? U extends any[] ? Flatten<U> : U[] : T;'s recursive conditional
type Flatten<T> = T extends (infer U)[] ? U extends any[] ? Flatten<U> : U[] : T; checks ifTis an array ofU. IfUis itself an array, it recursively callsFlatten<U>. Otherwise, it returnsU[]. This matches the requirement.Final Answer:
type Flatten<T> = T extends (infer U)[] ? U extends any[] ? Flatten<U> : U[] : T; -> Option DQuick Check:
Recursive infer for nested arrays = B [OK]
- Not handling recursion for nested arrays
- Returning wrong type shape after unwrapping
- Misplacing infer or conditional checks
Ready to prove it?
Pass the test and this pattern moves unknown
