JavaScript and TypeScript course ยท Module 7: Advanced TypeScript
Class Decorators
In this lesson9
"In Jurassic Park, every building and piece of infrastructure must be properly labeled and secured," explains John Hammond, walking through the newly built Visitor Center. "Some areas are accessible to everyone, others only to personnel with appropriate clearances, and still others require special security protocols. Without a proper system of labels and safeguards, there would be chaos."
In TypeScript, just like in Jurassic Park, we need a way to label and modify classes without interfering with their internal implementation. Class decorators are like special labels and security protocols that we can apply to classes to add extra functionality or characteristics.
Introduction to class decorators
Class decorators allow modifying or extending classes in a declarative way. They are especially useful when we want to:
- Add metadata to a class
- Automatically register a class in a registry
- Add methods or properties to a class
- Change constructor behavior
- Apply design patterns like Singleton or Factory
A class decorator is simply a function that takes a class constructor as an argument and can modify, extend, or completely replace it.
A note on versions: the examples in this lesson and the next two use the legacy decorators mode, switched on by the "experimentalDecorators": true option in tsconfig.json. NestJS and TypeORM, among others, rely on this mode. Since TypeScript 5.0, without that option you get standard ECMAScript decorators, which receive two arguments: the decorated value and a context object.
Basic class decorator syntax
Class decorators are placed above the class definition, preceded by the @ symbol:
@decorator
class MyClass {
// class implementation
}Where decorator is a function:
function decorator(target: Function) {
// Modification or extension of the class
}Example: Monitoring system in Jurassic Park
Let's start with a simple class decorator that will mark objects requiring monitoring in Jurassic Park:
// Class decorator
function Monitored(target: Function) {
// Add a property to the class prototype
target.prototype.monitored = true;
// Add a method to the class prototype
target.prototype.startMonitoring = function() {
console.log(`Monitoring started: ${this.name || this.constructor.name}`);
};
}
// Using the decorator
@Monitored
class DinosaurEnclosure {
name: string;
constructor(name: string) {
this.name = name;
}
addDinosaur(dinosaur: string) {
console.log(`Added ${dinosaur} to enclosure ${this.name}`);
}
}
// Using the class with the decorator
const raptorEnclosure = new DinosaurEnclosure("Velociraptor");
raptorEnclosure.addDinosaur("Blue");
// Now we can use the properties and methods added by the decorator
if ((raptorEnclosure as any).monitored) {
(raptorEnclosure as any).startMonitoring();
}In this example, the Monitored decorator adds a monitored property and a startMonitoring method to the prototype of the DinosaurEnclosure class. Thanks to this, all instances of this class will have access to these additional features.
Class decorators with parameters
We can also create decorators that accept parameters. In this case, our decorator function must return another function, which will be the actual decorator:
// Decorator factory
function SecurityLevel(level: number) {
// We return the actual class decorator
return function(target: Function) {
// Add a property to the class (not to the prototype)
target.prototype.securityLevel = level;
// Add an access verification method
target.prototype.checkAccess = function(employeeLevel: number): boolean {
return employeeLevel >= level;
};
// We can also override the constructor
const originalConstructor = target;
// Function replacing the constructor
function newConstructor(...args: any[]) {
console.log(`Creating object with security level: ${level}`);
// Call the original constructor
const instance = new (originalConstructor as any)(...args);
// Additional logic can be added
if (level >= 4) {
console.log("WARNING: Creating high security level object!");
}
return instance;
}
// Copy prototype properties
newConstructor.prototype = originalConstructor.prototype;
// Return the new constructor
return newConstructor as any;
};
}
// Using the decorator with a parameter
@SecurityLevel(4)
class GeneticLaboratory {
name: string;
constructor(name: string) {
this.name = name;
console.log(`Laboratory created: ${name}`);
}
cloneDinosaur(species: string) {
console.log(`Cloning ${species} in laboratory ${this.name}`);
}
}
// Using the class with the decorator
const laboratory = new GeneticLaboratory("Hammond Lab");
// Checking the security level
console.log(`Security level: ${(laboratory as any).securityLevel}`);
// Verifying access
const employeeLevel = 3;
if ((laboratory as any).checkAccess(employeeLevel)) {
console.log("Access granted to laboratory");
laboratory.cloneDinosaur("Velociraptor");
} else {
console.log("Access denied! Higher security level required.");
}In this example, the SecurityLevel decorator takes a parameter specifying the required access level. It adds a securityLevel property and a checkAccess method to the class, and also overrides the constructor to add additional logging.
Combining multiple decorators
We can apply multiple decorators to a single class. In this case, decorators are applied from bottom to top (from last to first):
// Decorator that registers in the system
function Registered(target: Function) {
console.log(`Registering class: ${target.name}`);
(target as any).registered = true;
}
// Decorator that adds logging
function Logged(prefix: string) {
return function(target: Function) {
// Save original methods
const originalMethods: Record<string, Function> = {};
// Iterate over prototype methods
for (const propertyName of Object.getOwnPropertyNames(target.prototype)) {
const descriptor = Object.getOwnPropertyDescriptor(target.prototype, propertyName);
// Check if it's a method and not a constructor
if (descriptor && typeof descriptor.value === 'function' && propertyName !== 'constructor') {
originalMethods[propertyName] = descriptor.value;
// Override the method, adding logging
Object.defineProperty(target.prototype, propertyName, {
value: function(...args: any[]) {
console.log(`${prefix}: Calling ${propertyName} with arguments: ${JSON.stringify(args)}`);
const result = originalMethods[propertyName].apply(this, args);
console.log(`${prefix}: ${propertyName} returned: ${JSON.stringify(result)}`);
return result;
}
});
}
}
};
}
// Using multiple decorators
@Registered
@SecurityLevel(3)
@Logged("[Gate control system]")
class GateControlSystem {
state: "open" | "closed" = "closed";
constructor() {
console.log("Initializing gate control system.");
}
openGates(): boolean {
console.log("Opening park gates...");
this.state = "open";
return true;
}
closeGates(): boolean {
console.log("Closing park gates...");
this.state = "closed";
return true;
}
checkStatus(): string {
return `Gates are ${this.state}`;
}
}
// Using the class with multiple decorators
const gateControl = new GateControlSystem();
gateControl.openGates();
console.log(gateControl.checkStatus());
gateControl.closeGates();In this example, the GateControlSystem class has three decorators applied:
@Registered- registers the class in the system@SecurityLevel(3)- sets the security level to 3@Logged("[Gate control system]")- adds logging to all class methods
Practical example: Park management system
Below is a more elaborate example of a Jurassic Park management system using various class decorators:
// Basic interface for all park resources
interface ParkResource {
id: string;
name: string;
location: string;
status: "active" | "inactive" | "maintenance" | "failure";
}
// Park resource registry
class ResourceRegistry {
private static registry: Map<string, ParkResource[]> = new Map();
static registerResource(type: string, resource: ParkResource): void {
if (!this.registry.has(type)) {
this.registry.set(type, []);
}
this.registry.get(type)!.push(resource);
console.log(`Resource registered: ${resource.name} (${type})`);
}
static getResources(type: string): ParkResource[] {
return this.registry.get(type) || [];
}
static getAllResources(): Map<string, ParkResource[]> {
return new Map(this.registry);
}
}
// Decorator for resource registration
function RegisterResource(type: string) {
return function<T extends { new(...args: any[]): ParkResource }>(constructor: T) {
return class extends constructor {
constructor(...args: any[]) {
super(...args);
ResourceRegistry.registerResource(type, this);
}
};
};
}
// Decorator enforcing audits
function RequiresAudit(frequencyDays: number) {
return function(target: Function) {
target.prototype.lastAudit = new Date();
target.prototype.auditFrequency = frequencyDays;
target.prototype.requiresAudit = function(): boolean {
const now = new Date();
const timeDifference = now.getTime() - this.lastAudit.getTime();
const differenceDays = timeDifference / (1000 * 3600 * 24);
return differenceDays >= this.auditFrequency;
};
target.prototype.performAudit = function(): void {
console.log(`Audit conducted for: ${this.name}`);
this.lastAudit = new Date();
};
};
}
// Decorator adding status history tracking
function TrackStatuses(target: Function) {
// Add status history array
target.prototype.statusHistory = [];
// Save original status setter
const originalSetStatus = Object.getOwnPropertyDescriptor(
target.prototype, 'status'
)?.set;
// Override the setter for status
if (originalSetStatus) {
Object.defineProperty(target.prototype, 'status', {
set: function(newStatus: "active" | "inactive" | "maintenance" | "failure") {
const oldTime = new Date();
const oldStatus = this._status;
// Call the original setter
originalSetStatus.call(this, newStatus);
// Save the change in history
this.statusHistory.push({
changeTime: oldTime,
from: oldStatus,
to: newStatus
});
console.log(`Status changed for ${this.name}: ${oldStatus || 'none'} -> ${newStatus}`);
},
get: Object.getOwnPropertyDescriptor(target.prototype, 'status')?.get
});
}
}
// Singleton decorator
function Singleton<T extends { new(...args: any[]): any }>(constructor: T) {
// Save original constructor
const originalConstructor = constructor;
// Replace constructor with a function that controls instance creation
const newConstructor: any = function(...args: any[]) {
if (!newConstructor.instance) {
newConstructor.instance = new originalConstructor(...args);
} else {
console.warn(`Singleton ${constructor.name} already exists. Returning existing instance.`);
}
return newConstructor.instance;
};
// Copy prototype
newConstructor.prototype = originalConstructor.prototype;
// Store original constructor
newConstructor.originalConstructor = originalConstructor;
return newConstructor;
}
// Implementation of various park resources
@RegisterResource("enclosure")
@RequiresAudit(7) // Audit every 7 days
@TrackStatuses
class DinosaursEnclosure implements ParkResource {
id: string;
name: string;
location: string;
private _status: "active" | "inactive" | "maintenance" | "failure" = "active";
// Enclosure-specific properties
genusDinosaurs: string;
capacity: number;
currentCount: number;
constructor(
id: string,
name: string,
location: string,
genusDinosaurs: string,
capacity: number
) {
this.id = id;
this.name = name;
this.location = location;
this.genusDinosaurs = genusDinosaurs;
this.capacity = capacity;
this.currentCount = 0;
}
get status(): "active" | "inactive" | "maintenance" | "failure" {
return this._status;
}
set status(newStatus: "active" | "inactive" | "maintenance" | "failure") {
this._status = newStatus;
}
addDinosaur(): boolean {
if (this.currentCount < this.capacity && this.status === "active") {
this.currentCount++;
console.log(`Dinosaur added to enclosure ${this.name}. Current count: ${this.currentCount}`);
return true;
} else {
console.log(`Cannot add dinosaur to enclosure ${this.name}. Enclosure full or inactive.`);
return false;
}
}
removeDinosaur(): boolean {
if (this.currentCount > 0) {
this.currentCount--;
console.log(`Dinosaur removed from enclosure ${this.name}. Current count: ${this.currentCount}`);
return true;
} else {
console.log(`Cannot remove dinosaur from enclosure ${this.name}. Enclosure empty.`);
return false;
}
}
}
@RegisterResource("building")
@RequiresAudit(30) // Audit every 30 days
@TrackStatuses
class ParkBuilding implements ParkResource {
id: string;
name: string;
location: string;
private _status: "active" | "inactive" | "maintenance" | "failure" = "active";
// Building-specific properties
genusBuilding: "public" | "administration" | "laboratory" | "maintenance";
area: number;
constructor(
id: string,
name: string,
location: string,
genusBuilding: "public" | "administration" | "laboratory" | "maintenance",
area: number
) {
this.id = id;
this.name = name;
this.location = location;
this.genusBuilding = genusBuilding;
this.area = area;
}
get status(): "active" | "inactive" | "maintenance" | "failure" {
return this._status;
}
set status(newStatus: "active" | "inactive" | "maintenance" | "failure") {
this._status = newStatus;
}
open(): void {
if (this.status !== "active") {
console.log(`Cannot open building ${this.name}. Status: ${this.status}`);
return;
}
console.log(`Building ${this.name} opened`);
}
close(): void {
console.log(`Building ${this.name} closed`);
}
}
@Singleton
@RegisterResource("system")
class SecuritySystem implements ParkResource {
id: string;
name: string;
location: string;
private _status: "active" | "inactive" | "maintenance" | "failure" = "active";
// Security system-specific properties
emergencyProtocol: "normal" | "warning" | "threat" | "evacuation" = "normal";
constructor() {
this.id = "SYS-SEC-001";
this.name = "Main Security System";
this.location = "Control center";
}
get status(): "active" | "inactive" | "maintenance" | "failure" {
return this._status;
}
set status(newStatus: "active" | "inactive" | "maintenance" | "failure") {
this._status = newStatus;
if (newStatus !== "active" && this.emergencyProtocol === "normal") {
console.warn("WARNING: Security system is not active!");
this.setProtocol("warning");
}
}
setProtocol(protocol: "normal" | "warning" | "threat" | "evacuation"): void {
this.emergencyProtocol = protocol;
console.log(`Security protocol set to: ${protocol}`);
// Action implementation depending on the protocol
switch (protocol) {
case "normal":
console.log("All systems operating normally.");
break;
case "warning":
console.log("Increased staff alertness. Checking all systems.");
break;
case "threat":
console.log("WARNING: Threat detected! Staff to positions! Prepare for evacuation.");
break;
case "evacuation":
console.log("WARNING! WARNING! Immediate park evacuation! This is not a drill!");
break;
}
}
checkStatus(): void {
console.log(`Security system status: ${this.status}`);
console.log(`Current protocol: ${this.emergencyProtocol}`);
}
}
// Using classes with decorators
// Creating an enclosure
const enclosureT = new DinosaursEnclosure(
"ZAG-001",
"T-Rex Enclosure",
"Sector A",
"Tyrannosaurus Rex",
2
);
enclosureT.addDinosaur();
enclosureT.status = "maintenance";
enclosureT.status = "active";
// Creating a building
const visitorCenter = new ParkBuilding(
"BUD-001",
"Visitor Center",
"Main entrance",
"public",
2500
);
visitorCenter.open();
visitorCenter.status = "maintenance";
visitorCenter.status = "active";
// Creating the security system (Singleton)
const securitySystem1 = new SecuritySystem();
securitySystem1.checkStatus();
securitySystem1.setProtocol("warning");
// Attempting to create a second security system
const securitySystem2 = new SecuritySystem();
// Note that securitySystem1 === securitySystem2
// Checking audits
console.log(`T-Rex Enclosure requires audit: ${(enclosureT as any).requiresAudit()}`);
console.log(`Visitor Center requires audit: ${(visitorCenter as any).requiresAudit()}`);
// Conducting audit
if ((enclosureT as any).requiresAudit()) {
(enclosureT as any).performAudit();
}
// Getting all resources from registry
console.log("Park resource list:");
const allResources = ResourceRegistry.getAllResources();
for (const [type, resources] of allResources) {
console.log(`Type: ${type}, Count: ${resources.length}`);
resources.forEach(resource => {
console.log(` - ${resource.name} (${resource.status})`);
});
}
// Checking status history
console.log("T-Rex Enclosure status history:");
(enclosureT as any).statusHistory.forEach((change: any) => {
console.log(` ${change.changeTime.toLocaleString()}: ${change.from || 'initial'} -> ${change.to}`);
});This elaborate example demonstrates advanced use of class decorators:
@RegisterResource- automatically registers resources in a central registry@RequiresAudit- adds audit schedule tracking functionality@TrackStatuses- adds status change history@Singleton- ensures only one instance of a class can be created
When to use class decorators
Class decorators are especially useful:
- When you want to add cross-cutting functionality - when the same functionality needs to be added to many classes (so-called aspect-oriented programming)
- When implementing design patterns - such as Singleton, Factory, Observer
- For automatic registration - e.g., registering components in a dependency injection system
- For metaprogramming - when code should modify itself at runtime
- For adding metadata - which can later be used by a framework
Limitations and issues with class decorators
Class decorators also have certain limitations and issues:
- Harder debugging - code with many decorators can be more difficult to debug
- Typing problems - sometimes you need to use
as anyto avoid TypeScript issues - Hidden functionality - decorators can hide important functionality, making code harder to understand
- Application order - the order of applying decorators matters and can cause problems
- Specification changes - the decorator specification in JavaScript and TypeScript is still evolving
Summary
Class decorators in TypeScript are a powerful tool that allows adding, modifying, or replacing class functionality in a declarative way, without interfering with their internal implementation. Just as special security protocols in Jurassic Park help maintain order and control, class decorators help organize and extend code in a clear and systematic manner.
Class decorators are especially useful in large applications where cross-cutting functionality often needs to be implemented across many classes, such as logging, authorization, validation, or component registration. Thanks to them, we can create more modular, flexible, and maintainable code.
However, remember that like all powerful tools, class decorators should be used wisely. Overusing them can lead to code that is difficult to debug and understand. Always use them when they genuinely solve a problem, not just because they look elegant.
Code for this lesson: index.ts
// A complete park type system - Jurassic Park
console.log("=== ADVANCED PARK TYPE SYSTEM ===\n");
// ===========================================
// 1. Base types and interfaces
// ===========================================
interface Entity {
readonly id: string;
readonly createdAt: Date;
}
interface Dinosaur extends Entity {
name: string;
species: string;
weight: number;
diet: "carnivore" | "herbivore" | "omnivore";
dangerLevel: number;
}
interface Enclosure extends Entity {
name: string;
capacity: number;
securityLevel: number;
residents: string[];
}
interface StaffMember extends Entity {
name: string;
role: "ranger" | "veterinarian" | "researcher" | "security";
clearanceLevel: number;
}
// ===========================================
// 2. Mapped and conditional types
// ===========================================
type EntityMap = {
dinosaur: Dinosaur;
enclosure: Enclosure;
staff: StaffMember;
};
type EntityType = keyof EntityMap;
// Creating DTO types automatically
type CreateDTO<T extends Entity> = Omit<T, "id" | "createdAt">;
type UpdateDTO<T extends Entity> = Partial<Omit<T, "id" | "createdAt">>;
type ReadDTO<T extends Entity> = Readonly<T>;
// ===========================================
// 3. A generic repository with constraints
// ===========================================
class Repository<T extends Entity> {
private storage: Map<string, T> = new Map();
private counter = 0;
private prefix: string;
constructor(prefix: string) {
this.prefix = prefix;
}
create(data: CreateDTO<T>): T {
const id = `${this.prefix}-${String(++this.counter).padStart(3, "0")}`;
const entity = { ...data, id, createdAt: new Date() } as T;
this.storage.set(id, entity);
return entity;
}
findById(id: string): ReadDTO<T> | undefined {
return this.storage.get(id);
}
findAll(): ReadDTO<T>[] {
return Array.from(this.storage.values());
}
update(id: string, data: UpdateDTO<T>): T | undefined {
const existing = this.storage.get(id);
if (!existing) return undefined;
const updated = { ...existing, ...data } as T;
this.storage.set(id, updated);
return updated;
}
delete(id: string): boolean {
return this.storage.delete(id);
}
query(predicate: (item: T) => boolean): ReadDTO<T>[] {
return this.findAll().filter(item => predicate(item as T));
}
}
// ===========================================
// 4. An event system with conditional types
// ===========================================
type EventSeverity = "info" | "warning" | "critical";
type ParkEvent<S extends EventSeverity> = S extends "critical"
? { severity: S; message: string; requiresEvacuation: boolean; affectedZones: string[] }
: S extends "warning"
? { severity: S; message: string; affectedZones: string[] }
: { severity: S; message: string };
function createEvent<S extends EventSeverity>(
severity: S,
data: Omit<ParkEvent<S>, "severity">
): ParkEvent<S> {
return { severity, ...data } as ParkEvent<S>;
}
// ===========================================
// 5. A report system with mapped types
// ===========================================
type DinoReport = {
[K in keyof Omit<Dinosaur, "id" | "createdAt">]: {
label: string;
value: Dinosaur[K];
formatted: string;
};
};
function generateReport(dino: Dinosaur): DinoReport {
return {
name: { label: "Name", value: dino.name, formatted: dino.name },
species: { label: "Species", value: dino.species, formatted: dino.species },
weight: { label: "Weight", value: dino.weight, formatted: `${dino.weight} kg` },
diet: { label: "Diet", value: dino.diet, formatted: dino.diet === "carnivore" ? "Carnivore" : dino.diet === "herbivore" ? "Herbivore" : "Omnivore" },
dangerLevel: { label: "Danger", value: dino.dangerLevel, formatted: `${dino.dangerLevel}/10` }
};
}
// ===========================================
// Test
// ===========================================
// Repositories
const dinoRepo = new Repository<Dinosaur>("DINO");
const encRepo = new Repository<Enclosure>("ENC");
const staffRepo = new Repository<StaffMember>("STAFF");
// Creating dinosaurs
console.log("--- Creating entities ---");
const rex = dinoRepo.create({ name: "Rexy", species: "T-Rex", weight: 8000, diet: "carnivore", dangerLevel: 10 });
const blue = dinoRepo.create({ name: "Blue", species: "Velociraptor", weight: 15, diet: "carnivore", dangerLevel: 8 });
const patty = dinoRepo.create({ name: "Patty", species: "Brachiosaurus", weight: 50000, diet: "herbivore", dangerLevel: 1 });
const mainEnc = encRepo.create({ name: "T-Rex Zone", capacity: 2, securityLevel: 10, residents: [rex.id] });
const grant = staffRepo.create({ name: "Alan Grant", role: "researcher", clearanceLevel: 8 });
console.log(`Dinosaur: ${rex.id} - ${rex.name}`);
console.log(`Enclosure: ${mainEnc.id} - ${mainEnc.name}`);
console.log(`Staff member: ${grant.id} - ${grant.name}`);
// Update
console.log("\n--- Update ---");
const updatedRex = dinoRepo.update(rex.id, { weight: 8200 });
console.log(`${updatedRex?.name}: ${updatedRex?.weight}kg`);
// Query
console.log("\n--- Queries ---");
const dangerousDinos = dinoRepo.query(d => d.dangerLevel >= 7);
console.log("Dangerous:", dangerousDinos.map(d => d.name).join(", "));
const carnivores = dinoRepo.query(d => d.diet === "carnivore");
console.log("Carnivores:", carnivores.map(d => d.name).join(", "));
// Events
console.log("\n--- Events ---");
const info = createEvent("info", { message: "Routine inspection completed" });
console.log("Info:", info.message);
const warning = createEvent("warning", {
message: "Fence needs repair",
affectedZones: ["Zone A"]
});
console.log("Warning:", warning.message, "Zones:", warning.affectedZones.join(", "));
const critical = createEvent("critical", {
message: "Dinosaur escape!",
requiresEvacuation: true,
affectedZones: ["Zone A", "Zone B"]
});
console.log("CRITICAL:", critical.message, "Evacuation:", critical.requiresEvacuation);
// Report
console.log("\n--- Dinosaur report ---");
const report = generateReport(rex);
Object.values(report).forEach(field => {
console.log(` ${field.label}: ${field.formatted}`);
});
console.log("\nA complete TypeScript type system in action!");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. Which utility type is used to EXCLUDE specific types from a union type?
2. What is a decorator in TypeScript?
Hands-on tasks in the game
- Vertical ordering
Order the steps for creating a custom utility type in TypeScript:
- Click in order
Arrange the elements of a class decorator declaration: