Performance: Generics in Angular services
Using generics in Angular services mainly affects bundle size and type safety without directly impacting rendering speed or layout performance.
export class DataService<T> { fetchData(url: string): Observable<T> { return this.http.get<T>(url); } }
export class DataService { fetchData(url: string): Observable<any> { return this.http.get(url); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Service using 'any' type | 0 | 0 | 0 | [OK] Good for runtime but poor for maintainability |
| Service using generics with type parameter | 0 | 0 | 0 | [OK] Best for type safety and no runtime cost |
<T> in Angular services?<T> as a placeholder to allow services to handle different data types flexibly.class ClassName<T>.export class DataService<T> { }, which is valid for a generic service.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');
service.add('world');
console.log(service.getAll());string as the type, so items is an array of strings.getAll() returns the array with these two strings.export class DataService<T> {
private items: T[] = [];
add(item: T) { this.items.push(item); }
getAll(): T[] { return this.items; }
}
const service = new DataService();
service.add(123);<T>, so TypeScript cannot infer the type.T as any or cause errors, losing type safety.get<T> method allows specifying the expected data type for the response.T when callingget<T>(url), the returned Observable emits data typed as T, ensuring compile-time checks.get<T>(url: string): Observable<T> in the service method and specify type when calling. -> Option BPass the test and this pattern moves unknown