How would you create a reusable, generic Angular component using TypeScript, such as a list component that works with any data type?
Short answer
TypeScript generics let a component's input types adapt to whatever specific data type is actually passed in, letting you write one flexible list component that works correctly and safely whether it is displaying a list of strings, numbers, or custom objects, with full type…
Advertisement
AModel answer
TypeScript generics let a component's input types adapt to whatever specific data type is actually passed in, letting you write one flexible list component that works correctly and safely whether it is displaying a list of strings, numbers, or custom objects, with full type checking still applying.
@Component({
selector: 'app-generic-list',
template: `@for (item of items(); track $index) { <ng-container [ngTemplateOutlet]="itemTemplate()" [ngTemplateOutletContext]="{ $implicit: item }"></ng-container> }`
})
export class GenericListComponent<T> {
items = input.required<T[]>();
itemTemplate = input.required<TemplateRef<any>>();
}Real-world example
A design system builds a single generic list component that safely works for a list of product objects on one page and a list of plain usernames on another, with TypeScript correctly checking each usage differently based on the actual data type passed in.
Likely follow-ups
- How does TypeScript know what type T actually is in a specific usage of this component?
- When is it worth the extra complexity of making a component generic versus keeping it more specific?
Related topics