Generic constraints

Sometimes, we might need to restrict the use of a generic class. For example, we can add a new feature to the generic queue. The new feature is going to validate the entities before they are added to the queue.

One possible solution would be to use the typeof operator to identify the type of the generic type parameter T within a generic class or function:

class User { public name!: string; public surname!: string; } class Car { public manufacturer!: string; public model!: string; } class Queue<T> { private _items: T[] = []; public push(item: T) { if (item instanceof User) { if ( item.name === "" || item.surname === "" ) { throw new Error("Invalid user"); } } if (item instanceof Car) { if ( item.manufacturer === "" || item.model ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.