JavaScript and TypeScript course ยท Module 7: Advanced TypeScript
Generic Constraints
In this lesson9
"In Jurassic Park, not all dinosaurs can be placed in the same enclosures," explains Dr. Alan Grant, the park's chief paleontologist. "Herbivorous triceratops can live together, but we can't place them with predatory velociraptors. We need clear rules about which dinosaurs can be placed where."
In TypeScript, generic constraints work on a similar principle - they allow you to specify requirements for types that can be used with generic functions or classes. With them, we can create more precise and safe APIs, ensuring that only appropriate data types are accepted.
Generic Constraint Basics
We create generic constraints using the extends keyword. This allows us to limit the range of possible types that can be used as type arguments.
Example: Simple Generic Constraint
Let's consider a function that should display basic information about a dinosaur. Instead of accepting any type, we want to make sure that the type passed to the function has at least the name and species properties:
// Generic constraint - type T must have at least the name and species properties
function displayDinosaurInfo<T extends { name: string; species: string }>(dino: T): void {
console.log(`Name: ${dino.name}, Species: ${dino.species}`);
}
// Works because the object contains the required properties
displayDinosaurInfo({ name: "Blue", species: "Velociraptor", age: 5 });
// Also works with more complex objects, as long as they contain the required properties
displayDinosaurInfo({
name: "Rex",
species: "Tyrannosaurus Rex",
age: 7,
weight: 8000,
dangerLevel: "Extreme"
});
// Compilation error - missing required property 'species'
// displayDinosaurInfo({ name: "Charlie", age: 4 });In this example, T extends { name: string; species: string } means that the generic type T must contain at least the properties name and species of the appropriate type. We can pass an object with additional properties, but these two are required.
Constraints on Interfaces and Types
We often define interfaces or types and then use them as constraints for our generic types:
// Defining a basic interface
interface DinosaurBase {
id: string;
name: string;
species: string;
age: number;
}
// Function with a generic constraint based on an interface
function addToRegistry<T extends DinosaurBase>(dino: T): void {
console.log(`Added to registry: ${dino.name} (ID: ${dino.id})`);
// Here we could add the dinosaur to the database, etc.
}
// Works because the object implements DinosaurBase
addToRegistry({
id: "V-001",
name: "Delta",
species: "Velociraptor",
age: 6,
trainingLevel: 3 // Additional property is ok
});
// Compilation error - missing required property 'age'
// addToRegistry({
// id: "T-001",
// name: "Rexy",
// species: "Tyrannosaurus"
// });Constraints for Generic Classes
Generic constraints are especially useful in generic classes, where we want to ensure that types used with the class meet specific requirements:
// Interface for animals that can be tracked
interface Trackable {
id: string;
lastKnownLocation: { x: number; y: number };
attachTracker(trackerId: string): void;
}
// Generic class with a constraint
class DinosaurTracker<T extends Trackable> {
private trackedEntities: T[] = [];
addEntity(entity: T): void {
// We can safely use methods from the Trackable interface
entity.attachTracker(`TRK-${Date.now()}`);
this.trackedEntities.push(entity);
console.log(`Started tracking: ID ${entity.id} at position (${entity.lastKnownLocation.x}, ${entity.lastKnownLocation.y})`);
}
updateLocation(id: string, x: number, y: number): void {
const entity = this.trackedEntities.find(e => e.id === id);
if (entity) {
entity.lastKnownLocation = { x, y };
console.log(`Updated position ${id}: (${x}, ${y})`);
}
}
getEntities(): readonly T[] {
return [...this.trackedEntities];
}
}
// Implementation of a dinosaur class that meets the Trackable interface requirements
class Velociraptor implements Trackable {
id: string;
name: string;
lastKnownLocation: { x: number; y: number };
private tracker: string | null = null;
constructor(id: string, name: string, initialX: number, initialY: number) {
this.id = id;
this.name = name;
this.lastKnownLocation = { x: initialX, y: initialY };
}
attachTracker(trackerId: string): void {
this.tracker = trackerId;
console.log(`Attached tracker ${trackerId} to velociraptor ${this.name}`);
}
hunt(): void {
// Hunting logic
console.log(`${this.name} is hunting nearby (${this.lastKnownLocation.x}, ${this.lastKnownLocation.y})`);
}
}
// Using the tracker with velociraptors
const raptorTracker = new DinosaurTracker<Velociraptor>();
const blue = new Velociraptor("V-001", "Blue", 120, 340);
const charlie = new Velociraptor("V-002", "Charlie", 125, 330);
raptorTracker.addEntity(blue);
raptorTracker.addEntity(charlie);
// We can use Velociraptor-specific methods because we know the concrete type
const raptors = raptorTracker.getEntities();
raptors.forEach(raptor => raptor.hunt());
// Simulating movement
raptorTracker.updateLocation("V-001", 140, 360);Constraints with Multiple Requirements
Sometimes we need a generic type to satisfy requirements from multiple interfaces or types. We can use the & sign (intersection type) to combine constraints:
// Two interfaces representing different aspects of park dynamics
interface Identifiable {
id: string;
serialNumber?: string;
}
interface Statusable {
status: "active" | "inactive" | "maintenance";
lastStatusUpdate: Date;
updateStatus(newStatus: "active" | "inactive" | "maintenance"): void;
}
// Generic function that requires the type to satisfy both interfaces
function performMaintenanceCheck<T extends Identifiable & Statusable>(entity: T): void {
console.log(`Starting review for ${entity.id}`);
if (entity.status !== "maintenance") {
entity.updateStatus("maintenance");
console.log(`Status updated to "maintenance" at ${entity.lastStatusUpdate.toLocaleTimeString()}`);
}
// Simulation of inspection
setTimeout(() => {
entity.updateStatus("active");
console.log(`Review completed for ${entity.id}. Status: active`);
}, 2000);
}
// Class that implements both interfaces
class SecurityGate implements Identifiable, Statusable {
id: string;
serialNumber: string;
status: "active" | "inactive" | "maintenance";
lastStatusUpdate: Date;
constructor(id: string, serialNumber: string) {
this.id = id;
this.serialNumber = serialNumber;
this.status = "active";
this.lastStatusUpdate = new Date();
}
updateStatus(newStatus: "active" | "inactive" | "maintenance"): void {
this.status = newStatus;
this.lastStatusUpdate = new Date();
// Additional logic specific to the gate
if (newStatus === "active") {
console.log(`Gate ${this.id} is now active and secured`);
} else if (newStatus === "inactive") {
console.log(`WARNING: Gate ${this.id} is inactive. Security threat!`);
}
}
// Method specific to the gate
toggleLock(locked: boolean): void {
console.log(`Gate ${this.id} is now ${locked ? "locked" : "unlocked"}`);
}
}
// Using the function with an object that satisfies both constraints
const mainGate = new SecurityGate("GATE-001", "SN123456");
performMaintenanceCheck(mainGate);
// Additional functionality available due to knowing the full type
mainGate.toggleLock(true);Constraints with Variant Elements (keyof)
The keyof operator in TypeScript allows us to obtain the union of an object's keys as a type. We can combine this with generic constraints to create functions that operate on specific properties of objects:
// Function that takes an object and a field name, then returns the value of that field
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// Example object with dinosaur data
const trex = {
name: "Rexy",
species: "Tyrannosaurus Rex",
age: 7,
diet: "carnivore",
threatLevel: 9,
enclosureId: "E-005"
};
// Correct usage - 'name' is a key of the trex object
const dinoName = getProperty(trex, "name");
console.log(dinoName); // "Rexy"
// Correct usage - 'age' is a key of the trex object
const dinoAge = getProperty(trex, "age");
console.log(dinoAge); // 7
// Compilation error - 'habitat' is not a key of the trex object
// const habitat = getProperty(trex, "habitat");This constraint ensures that the key K is actually a property name of the object T. TypeScript also knows what value type will be returned: T[K] (the value type at key K in an object of type T).
Practical Example: Reporting System for Jurassic Park
Let's see a more complex example that uses various aspects of generic constraints in the context of a reporting system for Jurassic Park:
// --- Base type definitions ---
// Base interface for all park resources
interface ParkResource {
id: string;
name: string;
lastUpdated: Date;
}
// Interface for report generation
interface Reportable {
generateReport(): string;
}
// Interface for manageable resources
interface Manageable {
assignTo(employeeId: string): void;
getAssignee(): string | null;
}
// --- Specific resource types ---
interface Dinosaur extends ParkResource {
species: string;
diet: "carnivore" | "herbivore" | "omnivore";
healthStatus: "healthy" | "sick" | "critical";
enclosureId: string;
}
interface Employee extends ParkResource {
role: string;
department: "research" | "security" | "operations" | "visitor";
clearanceLevel: 1 | 2 | 3 | 4 | 5;
}
interface Facility extends ParkResource {
type: "enclosure" | "lab" | "visitor_center" | "power_plant";
status: "operational" | "maintenance" | "construction";
location: { x: number; y: number };
}
// --- Reporting system implementation ---
// Generic base class for all repositories
class ResourceRepository<T extends ParkResource> {
protected resources: Map<string, T> = new Map();
add(resource: T): void {
this.resources.set(resource.id, {
...resource,
lastUpdated: new Date()
});
}
get(id: string): T | undefined {
return this.resources.get(id);
}
getAll(): T[] {
return Array.from(this.resources.values());
}
update(id: string, updates: Partial<T>): boolean {
const resource = this.resources.get(id);
if (!resource) return false;
this.resources.set(id, {
...resource,
...updates,
lastUpdated: new Date()
});
return true;
}
delete(id: string): boolean {
return this.resources.delete(id);
}
count(): number {
return this.resources.size;
}
}
// Class for manageable resources - adds assignment functionality
class ManageableResourceRepository<T extends ParkResource & Partial<Manageable>>
extends ResourceRepository<T> {
private assignments: Map<string, string> = new Map(); // resourceId -> employeeId
assignResource(resourceId: string, employeeId: string): boolean {
const resource = this.resources.get(resourceId);
if (!resource) return false;
this.assignments.set(resourceId, employeeId);
// If the resource implements Manageable, we call its assignTo method
if (resource.assignTo) {
resource.assignTo(employeeId);
}
return true;
}
getAssignee(resourceId: string): string | null {
// First, we check if the resource implements its own getAssignee method
const resource = this.resources.get(resourceId);
if (resource?.getAssignee) {
return resource.getAssignee();
}
// Otherwise, we use our internal map
return this.assignments.get(resourceId) || null;
}
getAssignedResources(employeeId: string): T[] {
const assigned: T[] = [];
this.assignments.forEach((assignedEmployeeId, resourceId) => {
if (assignedEmployeeId === employeeId) {
const resource = this.resources.get(resourceId);
if (resource) assigned.push(resource);
}
});
return assigned;
}
}
// Class for resources that can generate reports
class ReportableResourceRepository<T extends ParkResource & Reportable>
extends ResourceRepository<T> {
generateIndividualReport(id: string): string | null {
const resource = this.resources.get(id);
if (!resource) return null;
return resource.generateReport();
}
generateSummaryReport(): string {
const allResources = this.getAll();
let report = `SUMMARY REPORT
=======================
Total resources: ${allResources.length}
Last update: ${new Date().toLocaleString()}
=======================\n\n`;
allResources.forEach(resource => {
report += `${resource.name} (ID: ${resource.id}):\n`;
report += `${resource.generateReport()}\n\n`;
});
return report;
}
}
// --- Specific repository implementations ---
// Dinosaur repository
class DinosaurRepository extends ManageableResourceRepository<Dinosaur> {
// Methods specific to dinosaurs
findBySpecies(species: string): Dinosaur[] {
return this.getAll().filter(dino => dino.species === species);
}
findByDiet(diet: Dinosaur["diet"]): Dinosaur[] {
return this.getAll().filter(dino => dino.diet === diet);
}
findByEnclosure(enclosureId: string): Dinosaur[] {
return this.getAll().filter(dino => dino.enclosureId === enclosureId);
}
// Method generating a special report for dinosaurs
generateHealthStatusReport(): string {
const allDinos = this.getAll();
const healthy = allDinos.filter(d => d.healthStatus === "healthy").length;
const sick = allDinos.filter(d => d.healthStatus === "sick").length;
const critical = allDinos.filter(d => d.healthStatus === "critical").length;
return `
DINOSAUR HEALTH REPORT
=========================
Total: ${allDinos.length}
Healthy: ${healthy} (${Math.round(healthy / allDinos.length * 100)}%)
Sick: ${sick} (${Math.round(sick / allDinos.length * 100)}%)
Critical: ${critical} (${Math.round(critical / allDinos.length * 100)}%)
=========================
`;
}
}
// Employee repository
class EmployeeRepository extends ManageableResourceRepository<Employee> {
// Methods specific to employees
findByDepartment(department: Employee["department"]): Employee[] {
return this.getAll().filter(emp => emp.department === department);
}
findByClearanceLevel(level: Employee["clearanceLevel"]): Employee[] {
return this.getAll().filter(emp => emp.clearanceLevel === level);
}
}
// --- Example resource classes with reporting implementation ---
// Dinosaur class implementing Reportable
class ReportableDinosaur implements Dinosaur, Reportable {
id: string;
name: string;
species: string;
diet: "carnivore" | "herbivore" | "omnivore";
healthStatus: "healthy" | "sick" | "critical";
enclosureId: string;
lastUpdated: Date;
// Additional properties
private weight: number;
private height: number;
private behaviors: string[] = [];
constructor(
id: string,
name: string,
species: string,
diet: "carnivore" | "herbivore" | "omnivore",
healthStatus: "healthy" | "sick" | "critical",
enclosureId: string,
weight: number,
height: number
) {
this.id = id;
this.name = name;
this.species = species;
this.diet = diet;
this.healthStatus = healthStatus;
this.enclosureId = enclosureId;
this.weight = weight;
this.height = height;
this.lastUpdated = new Date();
}
addBehaviorObservation(behavior: string): void {
this.behaviors.push(`${new Date().toISOString()}: ${behavior}`);
this.lastUpdated = new Date();
}
generateReport(): string {
return `
--- DINOSAUR REPORT ---
ID: ${this.id}
Name: ${this.name}
Species: ${this.species}
Diet: ${this.diet}
Health status: ${this.healthStatus}
Enclosure: ${this.enclosureId}
Weight: ${this.weight} kg
Height: ${this.height} m
Recent behaviors: ${this.behaviors.length > 0 ? '\n - ' + this.behaviors.slice(-3).join('\n - ') : 'No recorded observations'}
-----------------------
`;
}
}
// --- Example usage ---
// Creating a repository for reportable dinosaurs
const reportableDinoRepo = new ReportableResourceRepository<ReportableDinosaur>();
// Adding dinosaurs to the repository
const rexReport = new ReportableDinosaur(
"D-001",
"Rexy",
"Tyrannosaurus Rex",
"carnivore",
"healthy",
"E-005",
8000,
5.2
);
const triceratopsReport = new ReportableDinosaur(
"D-002",
"Tricy",
"Triceratops",
"herbivore",
"sick",
"E-010",
6000,
3.0
);
// Adding behavior observations
rexReport.addBehaviorObservation("Ate an entire cow within 15 minutes");
rexReport.addBehaviorObservation("Territorial roar toward the Spinosaurus enclosure");
triceratopsReport.addBehaviorObservation("Weaker appetite than usual");
triceratopsReport.addBehaviorObservation("Signs of fever and drowsiness");
// Adding to repository
reportableDinoRepo.add(rexReport);
reportableDinoRepo.add(triceratopsReport);
// Generating reports
console.log(reportableDinoRepo.generateIndividualReport("D-001"));
console.log(reportableDinoRepo.generateSummaryReport());Limitations of Generic Constraints
Although generic constraints are a powerful tool, they have some limitations:
Incomplete type information at runtime - TypeScript uses generic constraints mainly at compile time. At runtime, type information is erased (type erasure).
Nominal vs structural constraints - TypeScript uses structural typing, which means objects with the same structure are considered compatible, even if they have different type names. Some programmers used to nominal typing (like in Java or C#) may find this unexpected.
No negative constraints - You cannot specify that a generic type must NOT have certain properties or must NOT implement a specific interface.
Despite these limitations, generic constraints are extremely useful in day-to-day TypeScript work.
When to Apply Generic Constraints?
Generic constraints are worth applying when:
You need to write functions or classes that work with different types but require those types to have certain common features.
You want to be sure that specific methods or properties will be available in types used with your generic components.
You need to create precise APIs that ensure type safety while maintaining flexibility.
You're implementing design patterns such as repositories, factories, or services that should work with different but related data types.
Summary
Generic constraints are an important tool in TypeScript that allows creating type-safe yet flexible components. They let you specify what requirements types used with generic functions and classes must meet, leading to more precise and reliable APIs.
Just like in Jurassic Park, where we need clear rules about which dinosaurs can be placed in which enclosures, generic constraints allow us to clearly define what types can be used with our generic components. This ensures the safety and predictability of our code while maintaining the flexibility that makes generics such a powerful tool.
Code for this lesson: index.ts
// Generic constraints - Jurassic Park
console.log("=== GENERIC CONSTRAINTS ===\n");
// ===========================================
// 1. extends - constraining a type
// ===========================================
interface HasName {
name: string;
}
interface HasWeight {
weight: number;
}
// T must have a 'name' field
function printName<T extends HasName>(entity: T): void {
console.log(`Name: ${entity.name}`);
}
// T must have both 'name' and 'weight'
function getHeaviest<T extends HasName & HasWeight>(items: T[]): T | undefined {
if (items.length === 0) return undefined;
return items.reduce((max, item) => item.weight > max.weight ? item : max);
}
// ===========================================
// 2. keyof - safe access to keys
// ===========================================
interface DinosaurProfile {
name: string;
species: string;
weight: number;
height: number;
dangerLevel: number;
}
// K must be a key of T
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// Getting many properties at once
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
const result = {} as Pick<T, K>;
keys.forEach(key => {
result[key] = obj[key];
});
return result;
}
// ===========================================
// 3. Constraints with default types
// ===========================================
interface Sortable {
compareTo?(other: this): number;
}
function sortEntities<T extends HasName>(
items: T[],
compareFn: (a: T, b: T) => number = (a, b) => a.name.localeCompare(b.name)
): T[] {
return [...items].sort(compareFn);
}
// ===========================================
// 4. Constraining the constructor
// ===========================================
interface Constructor<T> {
new (...args: any[]): T;
}
function createInstances<T extends HasName>(
Ctor: Constructor<T>,
count: number,
...args: any[]
): T[] {
const instances: T[] = [];
for (let i = 0; i < count; i++) {
instances.push(new Ctor(...args));
}
return instances;
}
// ===========================================
// Test
// ===========================================
const dinosaurs: DinosaurProfile[] = [
{ name: "Rexy", species: "T-Rex", weight: 8000, height: 5.5, dangerLevel: 10 },
{ name: "Blue", species: "Velociraptor", weight: 15, height: 1.8, dangerLevel: 8 },
{ name: "Patty", species: "Brachiosaurus", weight: 50000, height: 16, dangerLevel: 1 },
{ name: "Cera", species: "Triceratops", weight: 6000, height: 3, dangerLevel: 3 },
];
// extends
console.log("--- extends constraint ---");
printName({ name: "Rexy" }); // OK - it has a 'name' field
// printName({ age: 5 }); // Error! - no 'name'
const heaviest = getHeaviest(dinosaurs);
console.log(`Heaviest: ${heaviest?.name} (${heaviest?.weight}kg)`);
// keyof
console.log("\n--- keyof constraint ---");
const rex = dinosaurs[0];
console.log("Name:", getProperty(rex, "name"));
console.log("Weight:", getProperty(rex, "weight"));
// getProperty(rex, "color"); // Error! 'color' is not a key
const summary = pick(rex, ["name", "species", "dangerLevel"]);
console.log("Picked fields:", JSON.stringify(summary));
// Sorting with a constraint
console.log("\n--- sortEntities ---");
const sorted = sortEntities(dinosaurs);
console.log("Alphabetically:", sorted.map(d => d.name).join(", "));
const byDanger = sortEntities(dinosaurs, (a, b) => b.dangerLevel - a.dangerLevel);
console.log("By danger:", byDanger.map(d => `${d.name}(${d.dangerLevel})`).join(", "));
// Multiple constraints
console.log("\n--- Multiple constraints ---");
function describeEntity<T extends HasName & HasWeight>(entity: T): string {
return `${entity.name} weighs ${entity.weight}kg`;
}
dinosaurs.forEach(d => console.log(describeEntity(d)));
console.log("\nConstraints = safe generics with guaranteed types!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the notation <T extends { length: number }> mean in TypeScript?
2. What is a constraint in generics in TypeScript?
Hands-on tasks in the game
- Code editor
Use constraints for type-safe data access
- Horizontal ordering
Arrange the elements of keyof usage:
- Vertical ordering
Order the constraints from most general to most specific: