Skip to main content
InterviewHubPRO
Section Overview
Q17

Question 17 of 50

Part 2: Advanced Type System & Metaprogramming (Mid-Level)

34%
TypeScript Master (50 Qs)•Part 2: Advanced Type System & Metaprogramming (Mid-Level)

How does the `infer` keyword work in conditional types?

mid LevelCode ExampletypescriptAdvanced Type System

In Simple Words: infer allows you to declare a type variable inside the condition to extract or unwrap an unknown subtype:

typescript
// Extract return type of a function
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

function getUser() {
  return { id: 1, name: "Alice" };
}
type User = MyReturnType<typeof getUser>; // { id: number; name: string; }

// Unwrap a Promise
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type RawData = UnwrapPromise<Promise<string>>; // string