Challenge - 5 Problems
Generic Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a generic class instance method
What is the output of this TypeScript code when run with
console.log(box.getValue());?Typescript
class Box<T> { private value: T; constructor(value: T) { this.value = value; } getValue(): T { return this.value; } } const box = new Box<number>(123); console.log(box.getValue());
Attempts:
2 left
💡 Hint
Remember that the generic type is replaced by the actual type when creating an instance.
✗ Incorrect
The class Box stores a value of type T. Here, T is number, so getValue() returns 123 as a number.
❓ Predict Output
intermediate2:00remaining
Generic class with multiple type parameters
What will be the output of this code snippet?
Typescript
class Pair<T, U> { first: T; second: U; constructor(first: T, second: U) { this.first = first; this.second = second; } toString(): string { return `${this.first} and ${this.second}`; } } const pair = new Pair<string, number>("age", 30); console.log(pair.toString());
Attempts:
2 left
💡 Hint
Check the order of parameters and how template strings work.
✗ Incorrect
The toString method returns the first and second values joined by ' and '. The first is a string 'age', second is number 30.
🔧 Debug
advanced2:00remaining
Identify the error in generic class usage
What error will this TypeScript code produce?
Typescript
class Container<T> { content: T; constructor(content: T) { this.content = content; } getContent(): T { return this.content; } } const c = new Container(); console.log(c.getContent());
Attempts:
2 left
💡 Hint
Check if the generic type parameter is provided when creating an instance.
✗ Incorrect
The class Container requires a type argument when instantiated. Omitting it causes a compile-time error.
📝 Syntax
advanced2:00remaining
Correct syntax for generic class declaration
Which option shows the correct syntax to declare a generic class in TypeScript?
Attempts:
2 left
💡 Hint
Generic type parameters go after the class name, not the constructor.
✗ Incorrect
Option B correctly declares a generic class with type parameter T and uses it in the constructor parameter.
🚀 Application
expert2:00remaining
Determine the number of items in a generic class instance
Given this generic class and instance, how many items are in the
items array after execution?Typescript
class Collection<T> { items: T[] = []; add(item: T) { this.items.push(item); } } const numbers = new Collection<number>(); numbers.add(1); numbers.add(2); numbers.add(3);
Attempts:
2 left
💡 Hint
Count how many times add() is called with a number.
✗ Incorrect
The add method pushes each number into the items array. It is called three times, so items has length 3.