Lab 11: Decorators & Metadata

Objective

Write and use TypeScript decorators: class, method, property, and parameter decorators. Build a dependency injection container and validation framework using decorators.

Time

35 minutes

Prerequisites

  • Lab 04 (Classes), Lab 06 (Generics)

Tools

  • Docker image: zchencow/innozverse-ts:latest

  • Note: Requires "experimentalDecorators": true in tsconfig (enabled in the Docker image)


Lab Instructions

Step 1: Class Decorators

💡 Decorators execute bottom-up when stacked — @log("FACTORY") runs after @sealed. Class decorators receive the constructor function and can return a new class that extends it. This is how Angular's @Component, @Injectable, and @NgModule work.

📸 Verified Output:


Step 2: Method & Property Decorators

💡 Method decorators receive the class prototype, method name, and PropertyDescriptor. Replacing descriptor.value replaces the method with a wrapper. This is how @UseGuards, @Roles, @Cache work in NestJS — they wrap methods without modifying the class source code.

📸 Verified Output:


Steps 3–8: Property, Parameter, Reflect, DI Container, Validation Framework, Capstone

📸 Verified Output:


Summary

TypeScript decorators enable declarative programming — you annotate classes and methods with @decorator instead of modifying them directly. You've built memoization, validation, timing, a DI container, and a DTO validation system. This is exactly how Angular, NestJS, TypeORM, and class-validator work.

Further Reading

Last updated