Skip to Content
Learning TypeScript 2.x - Second Edition
book

Learning TypeScript 2.x - Second Edition

by Remo H. Jansen
April 2018
Beginner content levelBeginner
536 pages
13h 21m
English
Packt Publishing
Content preview from Learning TypeScript 2.x - Second Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering TypeScript - Fourth Edition

Mastering TypeScript - Fourth Edition

Nathan Rozentals
Learning TypeScript

Learning TypeScript

Josh Goldberg
TypeScript for Beginners

TypeScript for Beginners

Bharath Thippireddy

Publisher Resources

ISBN: 9781788391474Supplemental Content