0Pricing
Frontend Academy · Lesson

Decorators and Metadata

Enable experimental decorators, write class, method, and property decorators, and use reflect-metadata for dependency injection patterns.

Decorators and Metadata is a free Frontend Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Are Decorators?

Decorators are functions that modify classes, methods, properties, or parameters at definition time. They're used heavily in Angular, NestJS, TypeORM, and class-based MobX.

Decorator Syntax

Prefix a class, method, property, or parameter with @DecoratorName. The decorator function runs when the class is defined.

@Component({ selector: 'app-root' })
export class AppComponent {
  @Input() title: string;

  @HostListener('click')
  onClick() {
    console.log('clicked');
  }
}

Enabling Decorators

Enable the experimental flag in tsconfig.json. The new ECMAScript Stage 3 decorators (TypeScript 5.0+) don't need this flag but have different semantics.

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Class Decorator

Receives the constructor as its argument. Can replace, wrap, or augment the class.

function Singleton<T extends { new (...a: any[]): {} }>(target: T) {
  let instance: T;
  return class extends target {
    constructor(...args: any[]) {
      if (!instance) instance = new target(...args) as T;
      return instance;
    }
  };
}

@Singleton
class Logger { /* ... */ }

Method Decorator

Receives (target, key, descriptor). Can wrap the method — e.g., to log calls.

function Log(target: any, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`[${key}]`, args);
    return original.apply(this, args);
  };
}

class Service {
  @Log
  greet(name: string) { return `Hello ${name}`; }
}

Property Decorator

Receives (target, key). Often used with reflect-metadata to register information about the property.

function Required(target: any, key: string) {
  const existing = Reflect.getMetadata('required', target) || [];
  Reflect.defineMetadata('required', [...existing, key], target);
}

class User {
  @Required name: string;
  @Required email: string;
}

Parameter Decorator

Receives (target, key, parameterIndex). Used for dependency injection — recording which parameters need which services.

function Inject(token: string) {
  return function (target: any, key: string, index: number) {
    const existing = Reflect.getMetadata('inject', target, key) || {};
    existing[index] = token;
    Reflect.defineMetadata('inject', existing, target, key);
  };
}

class UserService {
  constructor(@Inject('Database') db: Database) {}
}

reflect-metadata

reflect-metadata is a polyfill that lets decorators read and write metadata on classes. Required for Angular DI and many ORMs.

npm install reflect-metadata

// main.ts (entry point):
import 'reflect-metadata';

import { Reflect } from 'reflect-metadata';
Reflect.defineMetadata('key', 'value', target);
Reflect.getMetadata('key', target); // 'value'

Decorator Factories

A factory returns a decorator — used to pass arguments.

function Component(config: { selector: string }) {
  return function (target: any) {
    target.selector = config.selector;
  };
}

@Component({ selector: 'app-root' })
class AppComponent {}

Validation Use Case

Combine property decorators with a validate() function to build a tiny validation library.

// Decorator records that a field is required:
function Required(target: any, key: string) {
  const fields = Reflect.getMetadata('required', target) || [];
  Reflect.defineMetadata('required', [...fields, key], target);
}

class User {
  @Required name!: string;
  @Required email!: string;
}

function validate(obj: any): string[] {
  const required: string[] = Reflect.getMetadata('required', obj) || [];
  return required.filter(k => obj[k] == null);
}

Stage 3 Decorators (TC39)

The standardised decorators (TS 5.0+, supported in Node 22+ behind a flag) have a different signature. They don't need the experimental flag and don't need reflect-metadata.

When to Use Decorators

Use decorators where the framework provides them (Angular, NestJS, TypeORM). Don't roll your own in plain frontend code — they add complexity and tie you to a specific runtime behaviour.

Quick Check

Which tsconfig flags must you enable to use legacy (experimental) decorators with metadata reflection?

Recap: Decorators

Decorators modify classes/methods/properties/parameters at definition time. Enable experimentalDecorators + emitDecoratorMetadata. Class, method, property, and parameter decorator signatures differ. reflect-metadata stores metadata; factories pass arguments. Heavily used by Angular, NestJS, TypeORM. Stage 3 decorators (TS 5+) are the future and don't need flags.

Frequently asked questions

Is the “Decorators and Metadata” lesson free?

Yes — the full text of “Decorators and Metadata” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.

What will I learn in “Decorators and Metadata”?

Enable experimental decorators, write class, method, and property decorators, and use reflect-metadata for dependency injection patterns. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Frontend Academy?

No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Decorators and Metadata” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Frontend Academy lesson?

Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Template Literal Types
  2. Decorators and Metadata
  3. TypeScript with React: FC generics hooks
  4. Strict Mode and Eliminating any
← Back to Frontend Academy