Generic Constraint

This lesson explains how to transform a generic type with a constraint to control what can be passed.

With generic, you can specify that the type passed into your generic class must extend a specific interface. Generic allows having code that can rely on a minimal interface without forcing a specific class.

For example, with a list, you do not need to force the list to hold a specific object. Instead, you can create a generic list where the generic type passed must extend a definition.

Function with constraints

In the following example, we are stating that any object that has at least a member named id of type number is allowed. By extending the generic type, you can perform logic on specific members; for example, access id regardless of the fields not exposed to the generic code.

Get hands-on with 1200+ tech skills courses.