Lab 04: Decorators

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Class, method, property, and parameter decorators. Decorator factories. Real-world logging and validation decorators.


Step 1: Setup with experimentalDecorators

docker run -it --rm node:20-alpine sh
npm install -g typescript ts-node
mkdir /lab04 && cd /lab04
cat > tsconfig.json << 'EOF'
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": false
  }
}
EOF

💡 experimentalDecorators: true enables the legacy Stage 2 decorator syntax. TypeScript 5.0+ also supports the new TC39 Stage 3 decorators, but experimentalDecorators remains widely used.


Step 2: Class Decorator


Step 3: Method Decorator


Step 4: Property Decorator


Step 5: Parameter Decorator


Step 6: Decorator Factories


Step 7: Real-World Logging Decorator


Step 8: Capstone — Full Decorator Suite

Run:

📸 Verified Output:


Summary

Decorator Type
Signature
Use Case

Class

(constructor: Function)

Seal, Singleton, metadata

Method

(target, key, descriptor)

Logging, caching, throttle

Property

(target, key)

Validation, readonly

Parameter

(target, key, index)

Validation metadata

Factory

(options) => decorator

Configurable decorators

Last updated