Bird
0
0

Given this Angular generic service snippet:

medium📝 component behavior Q4 of 15
Angular - TypeScript in Angular
Given this Angular generic service snippet:
export class DataService<T> {
  private items: T[] = [];
  add(item: T) { this.items.push(item); }
  getAll(): T[] { return this.items; }
}

const service = new DataService<string>();
service.add('hello');
console.log(service.getAll());

What will be logged to the console?
A['hello']
B['hello', undefined]
C[]
DError: Type mismatch
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the generic type used

    The service is created with string as the type parameter, so items is an array of strings.
  2. Step 2: Follow method calls

    The add method adds 'hello' to the array, then getAll returns the array with one string.
  3. Final Answer:

    ['hello'] -> Option A
  4. Quick Check:

    Generic type applied correctly = ['hello'] [OK]
Quick Trick: Generic service stores and returns typed items [OK]
Common Mistakes:
  • Expecting an empty array
  • Thinking undefined is added
  • Assuming type errors at runtime

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes