0
0
Typescriptprogramming~10 mins

Generic class syntax in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a generic class named Box.

Typescript
class Box[1] {
  content: T;
  constructor(value: T) {
    this.content = value;
  }
}
Drag options to blanks, or click blank then click option'
A(T)
B<T>
C[T]
D{T}
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or braces instead of angle brackets for generics.
Forgetting to add the generic parameter after the class name.
2fill in blank
medium

Complete the code to create an instance of the generic class Box with type number.

Typescript
const numberBox = new Box[1](123);
Drag options to blanks, or click blank then click option'
A<string>
B<any>
C<boolean>
D<number>
Attempts:
3 left
💡 Hint
Common Mistakes
Using a type that does not match the value passed to the constructor.
Omitting the generic type parameter.
3fill in blank
hard

Fix the error in the generic class declaration by completing the blank.

Typescript
class Pair[1] {
  first: T;
  second: U;
  constructor(first: T, second: U) {
    this.first = first;
    this.second = second;
  }
}
Drag options to blanks, or click blank then click option'
A<T, U>
B<T>
C<U>
D<T U>
Attempts:
3 left
💡 Hint
Common Mistakes
Using only one generic parameter when two are needed.
Missing the comma between generic parameters.
4fill in blank
hard

Fill both blanks to declare a generic class with two type parameters and a method returning the first value.

Typescript
class Container[1] {
  value1: T;
  value2: U;
  constructor(v1: T, v2: U) {
    this.value1 = v1;
    this.value2 = v2;
  }
  getFirst(): [2] {
    return this.value1;
  }
}
Drag options to blanks, or click blank then click option'
A<T, U>
BT
CU
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using only one generic parameter in the class declaration.
Returning the wrong generic type in the method.
5fill in blank
hard

Fill all three blanks to create a generic class with a method that swaps two values and returns a tuple.

Typescript
class Swapper[1] {
  a: T;
  b: U;
  constructor(a: T, b: U) {
    this.a = a;
    this.b = b;
  }
  swap(): [[2], [3]] {
    return [this.b, this.a];
  }
}
Drag options to blanks, or click blank then click option'
A<T, U>
BT
CU
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the tuple with the same order of types instead of swapped.
Using incorrect generic type syntax.