Challenge - 5 Problems
Generic Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a generic identity function
What is the output of this TypeScript code when calling
identity(42)?Typescript
function identity<T>(arg: T): T { return arg; } console.log(identity(42));
Attempts:
2 left
💡 Hint
The function returns exactly what it receives.
✗ Incorrect
The generic function
identity returns the argument it receives without changes. Passing 42 returns 42.❓ Predict Output
intermediate2:00remaining
Output of generic function with array argument
What will this code print to the console?
Typescript
function firstElement<T>(arr: T[]): T | undefined { return arr[0]; } console.log(firstElement(['apple', 'banana', 'cherry']));
Attempts:
2 left
💡 Hint
The function returns the first item of the array.
✗ Incorrect
The generic function returns the first element of the array passed. The first element is "apple".
❓ Predict Output
advanced2:00remaining
Output of generic function with multiple type parameters
What is the output of this code?
Typescript
function pairToString<K, V>(key: K, value: V): string { return `${key}: ${value}`; } console.log(pairToString<number, string>(1, "one"));
Attempts:
2 left
💡 Hint
The function formats key and value as a string separated by a colon.
✗ Incorrect
The function returns a string combining the key and value separated by ': '. The key is 1 and value is "one".
❓ Predict Output
advanced2:00remaining
Output of generic function with constraints
What will this code output?
Typescript
interface Lengthwise {
length: number;
}
function loggingLength<T extends Lengthwise>(arg: T): number {
return arg.length;
}
console.log(loggingLength('hello'));Attempts:
2 left
💡 Hint
Strings have a length property.
✗ Incorrect
The generic function requires the argument to have a length property. The string "hello" has length 5.
🧠 Conceptual
expert3:00remaining
Type inference in generic functions
Given the generic function
function wrap(value: T): { value: T } , what is the inferred type of T when calling wrap([1, 2, 3])?Attempts:
2 left
💡 Hint
The type parameter matches the argument's type exactly.
✗ Incorrect
The argument is an array of numbers, so TypeScript infers T as number[].