Bird
Raised Fist0
Typescriptprogramming~20 mins

Generic interface for collections in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Generic Collection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this generic collection interface usage?

Consider the following TypeScript code using a generic interface for a collection. What will be logged to the console?

Typescript
interface Collection<T> {
  add(item: T): void;
  get(index: number): T | undefined;
  size(): number;
}

class SimpleCollection<T> implements Collection<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  get(index: number): T | undefined {
    return this.items[index];
  }

  size(): number {
    return this.items.length;
  }
}

const numbers: Collection<number> = new SimpleCollection<number>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
console.log(numbers.get(1));
console.log(numbers.size());
A20\n3
B20\n2
Cundefined\n3
D10\n3
Attempts:
2 left
💡 Hint

Remember that arrays are zero-indexed and get(1) returns the second item.

🧠 Conceptual
intermediate
1:30remaining
Which statement about generic interfaces is true?

Choose the correct statement about generic interfaces in TypeScript.

AGeneric interfaces automatically infer the type without specifying it anywhere.
BGeneric interfaces can only be used with primitive types like number or string.
CGeneric interfaces cannot have methods that use the generic type parameter.
DGeneric interfaces allow you to define a contract that works with any data type specified when used.
Attempts:
2 left
💡 Hint

Think about how generics help reuse code for different types.

🔧 Debug
advanced
2:00remaining
What error does this code produce?

Examine the following TypeScript code. What error will the compiler report?

Typescript
interface Collection<T> {
  add(item: T): void;
  get(index: number): T;
}

class MyCollection<T> implements Collection<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  get(index: number): T {
    return this.items[index];
  }
}

const col = new MyCollection<number>();
console.log(col.get(0));
AError: Property 'get' may return undefined but signature requires 'T'.
BError: Cannot assign type 'number' to type 'T'.
CNo error, code runs and logs 'undefined'.
DError: Missing implementation of 'size' method.
Attempts:
2 left
💡 Hint

Think about what happens if the array is empty and you try to get an item.

📝 Syntax
advanced
1:30remaining
Which option correctly declares a generic interface for a collection?

Choose the correct syntax for declaring a generic interface named Collection with a method add that accepts an item of generic type T.

Ainterface Collection { add<T>(item: T): void; }
Binterface Collection<T> { add(item: T): void; }
Cinterface Collection<T> { add<T>(item: T): void; }
Dinterface Collection { add(item: T): void; }
Attempts:
2 left
💡 Hint

Remember that the generic parameter should be declared on the interface, not the method, for this case.

🚀 Application
expert
2:30remaining
How many items are in the resulting collection after this code runs?

Given the following code using a generic collection interface and class, how many items does the collection contain at the end?

Typescript
interface Collection<T> {
  add(item: T): void;
  remove(item: T): boolean;
  size(): number;
}

class AdvancedCollection<T> implements Collection<T> {
  private items: T[] = [];

  add(item: T): void {
    if (!this.items.includes(item)) {
      this.items.push(item);
    }
  }

  remove(item: T): boolean {
    const index = this.items.indexOf(item);
    if (index >= 0) {
      this.items.splice(index, 1);
      return true;
    }
    return false;
  }

  size(): number {
    return this.items.length;
  }
}

const col = new AdvancedCollection<string>();
col.add("apple");
col.add("banana");
col.add("apple");
col.remove("banana");
col.add("cherry");
col.remove("date");
A1
B3
C2
D4
Attempts:
2 left
💡 Hint

Consider how duplicates are handled and what happens when removing items not in the collection.

Practice

(1/5)
1. What does the <T> represent in a generic interface in TypeScript?
easy
A. A function inside the interface
B. A fixed type like number or string
C. A placeholder for any type that will be specified later
D. A variable name for a property

Solution

  1. Step 1: Understand generic syntax

    The <T> in TypeScript generics is a placeholder representing any type that will be provided when the interface is used.
  2. Step 2: Differentiate from fixed types

    Unlike fixed types like number or string, T is flexible and can represent any type, making the interface reusable.
  3. Final Answer:

    A placeholder for any type that will be specified later -> Option C
  4. Quick Check:

    Generic <T> = placeholder type [OK]
Hint: Remember <T> means 'any type' placeholder [OK]
Common Mistakes:
  • Thinking T is a fixed type
  • Confusing T with a function
  • Assuming T is a variable name
2. Which of the following is the correct syntax to declare a generic interface named Collection with a type parameter T?
easy
A. interface Collection<T> { items: T[]; }
B. interface Collection { items: T[]; }
C. interface Collection<T> { items: Array; }
D. interface Collection<T> { items: T; }

Solution

  1. Step 1: Check generic declaration

    The correct syntax to declare a generic interface uses <T> after the interface name, like interface Collection<T>.
  2. Step 2: Verify property type

    The property items should be an array of type T, so items: T[] is correct.
  3. Final Answer:

    interface Collection<T> { items: T[]; } -> Option A
  4. Quick Check:

    Generic interface syntax = interface Collection<T> { items: T[]; } [OK]
Hint: Generic interface needs <T> and array type T[] [OK]
Common Mistakes:
  • Omitting <T> after interface name
  • Using Array without type parameter
  • Declaring items as single T instead of array
3. Given the interface and usage below, what is the output of console.log(numbers.items[1])?
interface Collection<T> {
  items: T[];
}
const numbers: Collection<number> = { items: [10, 20, 30] };
console.log(numbers.items[1]);
medium
A. 10
B. 20
C. 30
D. undefined

Solution

  1. Step 1: Understand the generic interface usage

    The interface Collection<T> is used with number, so items is an array of numbers: [10, 20, 30].
  2. Step 2: Access the second element in the array

    Arrays are zero-indexed, so items[1] is the second element, which is 20.
  3. Final Answer:

    20 -> Option B
  4. Quick Check:

    Array index 1 = 20 [OK]
Hint: Remember arrays start at index 0 [OK]
Common Mistakes:
  • Confusing index 1 with index 0
  • Assuming generic changes array order
  • Expecting undefined for valid index
4. Identify the error in this code snippet using a generic interface:
interface Collection<T> {
  items: T[];
}
const strings: Collection<string> = { items: [1, 2, 3] };
medium
A. The array items contain numbers, but the interface expects strings
B. The interface is missing the generic type parameter
C. The variable strings should be declared with type number
D. The interface property items should not be an array

Solution

  1. Step 1: Check the generic type used

    The variable strings is declared as Collection<string>, so items must be an array of strings.
  2. Step 2: Check the assigned array type

    The assigned array is [1, 2, 3], which is an array of numbers, not strings, causing a type mismatch error.
  3. Final Answer:

    The array items contain numbers, but the interface expects strings -> Option A
  4. Quick Check:

    Type mismatch in generic array = The array items contain numbers, but the interface expects strings [OK]
Hint: Check if array elements match generic type [OK]
Common Mistakes:
  • Ignoring type mismatch between generic and array
  • Forgetting to specify generic parameter
  • Assuming interface property can be non-array
5. You want to create a generic interface KeyValueCollection that stores key-value pairs where keys are strings and values can be any type T. Which interface definition correctly achieves this?
hard
A. interface KeyValueCollection<T> { [T: string]: string; }
B. interface KeyValueCollection<T> { keys: string[]; values: T[]; }
C. interface KeyValueCollection<T> { key: string; value: T; }
D. interface KeyValueCollection<T> { [key: string]: T; }

Solution

  1. Step 1: Understand key-value pair requirement

    The interface should allow any string as a key and associate it with a value of generic type T.
  2. Step 2: Check index signature syntax

    Using [key: string]: T; means any string key maps to a value of type T, which matches the requirement.
  3. Step 3: Eliminate other options

    interface KeyValueCollection<T> { keys: string[]; values: T[]; } separates keys and values arrays, which is less direct. interface KeyValueCollection<T> { key: string; value: T; } defines a single pair, not a collection. interface KeyValueCollection<T> { [T: string]: string; } has incorrect syntax.
  4. Final Answer:

    interface KeyValueCollection<T> { [key: string]: T; } -> Option D
  5. Quick Check:

    Index signature with generic value = interface KeyValueCollection<T> { [key: string]: T; } [OK]
Hint: Use index signature [key: string]: T for generic key-value [OK]
Common Mistakes:
  • Using arrays for keys and values separately
  • Defining only one key-value pair instead of collection
  • Incorrect index signature syntax
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard