Challenge - 5 Problems
TypeScript Generics Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this TypeScript code with generics?
Consider this TypeScript function that uses a generic type. What will be the output when calling
identity(42)?Typescript
function identity<T>(arg: T): T { return arg; } console.log(identity(42));
Attempts:
2 left
💡 Hint
TypeScript infers the generic type from the argument passed.
✗ Incorrect
The generic type is inferred as number because 42 is a number. The function returns the same value, so output is 42.
❓ Predict Output
intermediate2:00remaining
What type does TypeScript infer here?
Given this function call, what type does TypeScript infer for
T?Typescript
function wrapInArray<T>(value: T): T[] { return [value]; } const result = wrapInArray('hello');
Attempts:
2 left
💡 Hint
Look at the argument passed to the function.
✗ Incorrect
The argument is a string, so T is inferred as string. The function returns an array of T, so result is string[].
❓ Predict Output
advanced2:00remaining
What is the output of this generic function with multiple parameters?
What will this code print when run?
Typescript
function merge<T, U>(obj1: T, obj2: U): T & U { return {...obj1, ...obj2}; } const merged = merge({name: 'Alice'}, {age: 30}); console.log(merged);
Attempts:
2 left
💡 Hint
The function combines two objects using spread syntax.
✗ Incorrect
The function merges two objects into one. The result has properties from both inputs.
❓ Predict Output
advanced2:00remaining
What error does this code raise due to incorrect generic inference?
What error will this TypeScript code produce?
Typescript
function firstElement<T>(arr: T[]): T { return arr[0]; } const result = firstElement([]); console.log(result);
Attempts:
2 left
💡 Hint
TypeScript infers the empty array as never[], causing a type mismatch.
✗ Incorrect
TypeScript treats the empty array literal as never[] in this generic context, which is not assignable to T[], resulting in a compile-time type error.
🧠 Conceptual
expert3:00remaining
Which option best describes how TypeScript infers generic types in this scenario?
Given a generic function with multiple parameters, how does TypeScript infer the generic types when called with different argument types?
Attempts:
2 left
💡 Hint
Think about how TypeScript matches each generic parameter to each argument.
✗ Incorrect
TypeScript infers each generic type parameter separately from the corresponding argument's type, allowing flexible generic functions.