Bird
0
0

Identify the error in this Angular generic service code:

medium📝 Debug Q6 of 15
Angular - TypeScript in Angular
Identify the error in this Angular generic service code:
export class ListService<T> {
  private items: T[] = [];
  add(item: T) { this.items.push(item); }
  getAll(): T[] { return this.items; }
}

const service = new ListService();
service.add(5);
AMissing generic type argument when creating service instance
BIncorrect method name 'add' used
CArray initialization syntax is wrong
DCannot push item into array
Step-by-Step Solution
Solution:
  1. Step 1: Check service instantiation

    The service is created without specifying the generic type <T>, which is required.
  2. Step 2: Understand TypeScript generic rules

    Omitting the generic type causes a compile-time error because TypeScript cannot infer T.
  3. Final Answer:

    Missing generic type argument when creating service instance -> Option A
  4. Quick Check:

    Generic type must be specified on instantiation [OK]
Quick Trick: Always specify generic type when creating service instance [OK]
Common Mistakes:
  • Forgetting on new service()
  • Assuming generic type is optional
  • Confusing method names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes