SkillByAIOpen interactive version →

Lesson 26 / 28

Decorators at a Glance

Understand TypeScript decorators and how frameworks such as Angular use them to add metadata and behaviour.

What's a decorator?

A decorator is a special function, prefixed with @, that wraps a class or member to add behavior or metadata without changing its source. Angular uses them heavily — @Component, @Injectable, @Input.

A simple class decorator

A decorator is just a function that receives the class and can inspect or modify it.

function Logged(constructor: Function) {
  console.log(`Class defined: ${constructor.name}`);
}

@Logged
class Greeter {
  greet() {
    return "Hello!";
  }
}
// Output: Class defined: Greeter

Enable them in tsconfig

Legacy decorators need "experimentalDecorators": true in tsconfig.json — Angular CLI projects set this for you automatically.