0
0
Typescriptprogramming~10 mins

Generic interface for collections 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 interface named Collection.

Typescript
interface Collection<[1]> {
  add(item: T): void;
  remove(item: T): void;
  size(): number;
}
Drag options to blanks, or click blank then click option'
AT
BU
CV
DK
Attempts:
3 left
💡 Hint
Common Mistakes
Using a lowercase letter for the generic type parameter.
Forgetting to put the generic parameter in angle brackets.
2fill in blank
medium

Complete the code to declare a class that implements the generic Collection interface.

Typescript
class List<[1]> implements Collection<T> {
  private items: T[] = [];
  add(item: T): void {
    this.items.push(item);
  }
  remove(item: T): void {
    this.items = this.items.filter(i => i !== item);
  }
  size(): number {
    return this.items.length;
  }
}
Drag options to blanks, or click blank then click option'
AK
BV
CT
DU
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different generic parameter than the interface.
Not declaring the generic parameter on the class.
3fill in blank
hard

Fix the error in the method signature to correctly use the generic type parameter.

Typescript
remove(item: [1]): void {
  this.items = this.items.filter(i => i !== item);
}
Drag options to blanks, or click blank then click option'
Aany
BT
Cunknown
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-generic type like any or object.
Forgetting to use the generic type parameter.
4fill in blank
hard

Fill both blanks to create a generic function that returns the first item of a collection.

Typescript
function getFirst<[1]>(collection: Collection<T>): [2] | undefined {
  // Assume collection has a method to get all items as array
  const items = (collection as any).items as T[];
  return items[0];
}
Drag options to blanks, or click blank then click option'
AT
BU
DV
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic parameters in declaration and return type.
Not declaring the generic parameter in the function.
5fill in blank
hard

Fill all three blanks to define a generic interface with a method that returns an array of items.

Typescript
interface Collection<[1]> {
  add(item: T): void;
  getAll(): [2][];
  size(): [3];
}
Drag options to blanks, or click blank then click option'
AT
Bnumber
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using string instead of number for size.
Not using the generic type for the array return type.