EasyClasses & OOP📖 Theory Question

How do decorators work in TypeScript, and what are they used for?

💡

Hint

Decorators are factory functions applied to classes, methods, or properties — common for metadata, dependency injection, logging

Full Answer

Decorators are functions that wrap or modify classes, methods, properties, or parameters. Enabled with experimentalDecorators: true in tsconfig.

// Class decorator — modify or augment a class
function Singleton<T extends new(...args: any[]) => any>(Ctor: T) {
  let instance: InstanceType<T>;
  return class extends Ctor {
    constructor(...args: any[]) {
      if (instance) return instance;
      super(...args);
      instance = this as any;
    }
  };
}

@Singleton
class Config { /* only one instance ever created */ }

// Method decorator — wrap a method with extra behavior
function log(target: any, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${key} with`, args);
    const result = original.apply(this, args);
    console.log(`${key} returned`, result);
    return result;
  };
  return descriptor;
}

class Calculator {
  @log
  add(a: number, b: number): number {
    return a + b;
  }
}

// Property decorator — metadata annotation
function required(target: any, propertyKey: string) {
  // metadata stored here — used by validation frameworks
}

class User {
  @required
  name: string = '';
}
💡 Decorators are widely used in Angular, NestJS, TypeORM, and class-validator. TypeScript 5.0 introduced the new decorator standard (TC39 Stage 3) that differs from the legacy experimental decorators.

More Classes & OOP Questions

EasyWhat are access modifiers in TypeScript — public, private, protected, readonly?→EasyWhat are abstract classes in TypeScript and when should you use them?→EasyWhat is the difference between implements and extends in TypeScript?→MediumWhat are static members and class fields in TypeScript?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint