0
0
Typescriptprogramming~5 mins

Inferring types with infer keyword in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the infer keyword do in TypeScript?
The infer keyword lets TypeScript guess a type inside a conditional type. It helps extract or infer a type from another type.
Click to reveal answer
intermediate
How do you use infer inside a conditional type?
You write a conditional type with extends and inside it use infer T to capture a type part. For example: type GetReturn<T> = T extends (...args: any[]) => infer R ? R : never;
Click to reveal answer
beginner
What happens if the type does not match the pattern when using infer?
If the type does not match the pattern in the conditional type, the infer part is ignored and the false branch of the conditional type is used.
Click to reveal answer
intermediate
Give an example of inferring the argument type of a function using infer.
Example: type ArgType<T> = T extends (arg: infer A) => any ? A : never; This extracts the type of the first argument of a function type T.
Click to reveal answer
beginner
Why is infer useful in TypeScript?
infer helps create flexible and reusable types by extracting parts of complex types automatically. It reduces manual type writing and improves type safety.
Click to reveal answer
What does the infer keyword do in TypeScript conditional types?
AExtracts a type from another type
BDeclares a new variable
CCreates a new interface
DDefines a function
Which syntax correctly uses infer to get a function's return type?
Atype R<T> = T => infer R;
Btype R<T> = T extends (...args: any[]) => infer R ? R : never;
Ctype R<T> = T extends infer R ? R : never;
Dtype R<T> = infer R extends T ? R : never;
What happens if the type does not match the pattern when using infer?
AThe program crashes
BTypeScript throws an error
CThe inferred type becomes <code>any</code>
DThe <code>infer</code> type is ignored and the false branch is used
Which of these extracts the first argument type of a function using infer?
Atype Arg<T> = infer A extends T ? A : never;
Btype Arg<T> = T extends infer A => any ? A : never;
Ctype Arg<T> = T extends (arg: infer A) => any ? A : never;
Dtype Arg<T> = T => infer A;
Why is infer useful in TypeScript?
AIt helps extract types automatically for flexible type definitions
BIt runs code at runtime
CIt creates new variables
DIt replaces interfaces
Explain how the infer keyword works inside a TypeScript conditional type.
Think about how TypeScript guesses a type inside a condition.
You got /4 concepts.
    Give an example of using infer to extract the return type of a function type.
    Use a conditional type with <code>extends</code> and <code>infer R</code>.
    You got /4 concepts.