Generic constraints

Sometimes, we might need to restrict the use of a generic class. Take the generic repository from the previous section as an example. We have a new requirement: we need to add some changes to validate the entities loaded via AJAX, and we will return only the valid entities.

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

// ...
success: (data) => {
  var list : T[];
  var items = <T[]>data.items;
  for(var i = 0; i < items.length; i++){
    if(items[i] instanceof User) {
      // validate user
    }
    if(items[i] instanceof Talk) {
      // validate talk
    }
  }
  resolve(list);
}
// ...

The problem is that we will have to modify our GenericRepository class ...

Get TypeScript: Modern JavaScript Development 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.