0
0
Typescriptprogramming~20 mins

Generic class syntax in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generic Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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());
Aundefined
B"123"
CTypeError at runtime
D123
Attempts:
2 left
💡 Hint
Remember that the generic type is replaced by the actual type when creating an instance.
Predict Output
intermediate
2: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());
A"age and 30"
B"30 and age"
C"[object Object] and 30"
DTypeError at runtime
Attempts:
2 left
💡 Hint
Check the order of parameters and how template strings work.
🔧 Debug
advanced
2: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());
ANo error, outputs the content
BOutput: undefined
CError: Generic type 'Container' requires 1 type argument(s).
DOutput: null
Attempts:
2 left
💡 Hint
Check if the generic type parameter is provided when creating an instance.
📝 Syntax
advanced
2:00remaining
Correct syntax for generic class declaration
Which option shows the correct syntax to declare a generic class in TypeScript?
Aclass Data {<T> constructor(value: T) { this.value = value; } }
Bclass Data<T> { constructor(value: T) { this.value = value; } }
Cclass Data<T> { constructor<T>(value: T) { this.value = value; } }
Dclass Data<T> { constructor(value) { this.value = value; } }
Attempts:
2 left
💡 Hint
Generic type parameters go after the class name, not the constructor.
🚀 Application
expert
2: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);
A3
B1
C0
DTypeError at runtime
Attempts:
2 left
💡 Hint
Count how many times add() is called with a number.