0
0
Typescriptprogramming~20 mins

Inferring types with infer keyword in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Infer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this inferred type?
Consider the following TypeScript type using infer. What is the type of Result?
Typescript
type ExtractReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

type Func = (x: number) => string;
type Result = ExtractReturnType<Func>;

// What is the type of Result?
A"never"
B"number"
C"any"
D"string"
Attempts:
2 left
💡 Hint
Look at what the infer R captures inside the function type.
Predict Output
intermediate
2:00remaining
What is the inferred type from a tuple?
Given this type using infer, what is the type of First?
Typescript
type FirstElement<T> = T extends [infer U, ...any[]] ? U : never;

type Tuple = [boolean, number, string];
type First = FirstElement<Tuple>;

// What is the type of First?
A"boolean"
B"number"
C"string"
D"never"
Attempts:
2 left
💡 Hint
The infer U captures the first element of the tuple.
🔧 Debug
advanced
2:30remaining
Why does this infer type cause an error?
This code tries to infer the argument type of a function but causes a TypeScript error. What is the cause?
Typescript
type ArgType<T> = T extends (arg: infer A, arg2: infer B) => any ? A : never;

type Fn = (x: number, y: string) => void;
type Result = ArgType<Fn>;

// Why does this cause an error?
ABecause the syntax for multiple infer variables in parameters is invalid
BBecause the conditional type only returns the first inferred argument type, ignoring the second
CBecause only one infer variable is allowed per conditional type
DBecause the function type must have exactly one argument to use infer
Attempts:
2 left
💡 Hint
Check if multiple infer variables can be used in function parameters like this.
Predict Output
advanced
2:00remaining
What is the inferred type from nested infer?
What is the type of InnerType after this nested inference?
Typescript
type NestedReturnType<T> = T extends () => () => infer R ? R : never;

type Fn = () => () => number;
type InnerType = NestedReturnType<Fn>;

// What is InnerType?
A"() => number"
B"void"
C"number"
D"never"
Attempts:
2 left
💡 Hint
Look carefully at the nested function return types and what infer captures.
🧠 Conceptual
expert
3:00remaining
Which option correctly infers the element type of an array?
You want to create a type that extracts the element type from an array type using infer. Which option correctly does this?
Atype ElementType<T> = T extends (infer U)[] ? U : never;
Btype ElementType<T> = T extends Array<infer U> ? U : never;
Ctype ElementType<T> = T extends [infer U] ? U : never;
Dtype ElementType<T> = T extends { length: infer U } ? U : never;
Attempts:
2 left
💡 Hint
Remember how to match generic array types with infer.