Decorator Logger System
What you'll build
A method decorator that wraps any class method to log its name, arguments, and return value. Enable experimentalDecorators in tsconfig.
Goals
- Understand decorator syntax and experimentalDecorators
- Write a method decorator factory
- Preserve the original method's type signature
- Apply cross-cutting concerns declaratively
Prerequisites
- Classes in TypeScript
- Functions
- tsconfig settings
Steps
- 1
Enable decorator support
Add experimentalDecorators to tsconfig.json. Decorators are an experimental feature that requires explicit opt-in.
Code{ "compilerOptions": { "experimentalDecorators": true, "target": "ES2022" } }Expected result
tsconfig.json now supports decorator syntax.
- 2
Write the log decorator
Create a method decorator that replaces the original method with a logging wrapper. The wrapper calls the original, logs the result, and returns it.
Codefunction log(target: any, key: string, desc: PropertyDescriptor) { const original = desc.value; desc.value = function (...args: any[]) { console.log(`Calling ${key} with`, args); const result = original.apply(this, args); console.log(`${key} returned`, result); return result; }; }Expected result
A decorator function that wraps methods with logging.
- 3
Apply the decorator to a class
Use the @log decorator on class methods. Each decorated method now automatically logs its calls.
Codeclass Calculator { @log add(a: number, b: number) { return a + b; } @log multiply(a: number, b: number) { return a * b; } } const calc = new Calculator(); calc.add(2, 3); // logs: Calling add with [2, 3] / add returned 5Expected result
Method calls are automatically logged without modifying the method body.
- 4
Add type guards & runtime checks
Write a user-defined type guard function to validate data shape at runtime, combined with the unknown type to safely handle external input. Type guards give TypeScript runtime type safety too.
Codetype User = { id: number; name: string }; function isUser(value: unknown): value is User { if (typeof value !== "object" || value === null) return false; const obj = value as Record<string, unknown>; return typeof obj.id === "number" && typeof obj.name === "string"; } // Usage with unknown input const data: unknown = JSON.parse(rawJson); if (isUser(data)) { console.log(data.name); // TS knows data is User here } else { console.error("Invalid user data"); }Expected result
When isUser returns true, TS narrows data to User type; invalid data goes to the else branch.
- 5
Add generic utility functions
Write generic utility functions (e.g., deepFreeze, groupBy) to enhance type-safe reuse. Generics let utility functions work with multiple types without losing type information.
Codefunction groupBy<T, K extends string | number>( items: T[], keyFn: (item: T) => K ): Record<K, T[]> { const result = {} as Record<K, T[]>; for (const item of items) { const key = keyFn(item); (result[key] ??= []).push(item); } return result; } // Usage const byAge = groupBy(users, u => u.age);Expected result
groupBy groups any array by key, returning a type-safe Record.
Try it yourself
What you learned
You used decorators to add logging without modifying method bodies — a cross-cutting concern applied declaratively. Decorators are a powerful metaprogramming feature, though they require experimentalDecorators and have evolving standards.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.