TypeScript Decorators

Introduction to TypeScript Decorators

TypeScript decorators are a feature that allows you to add extra information or behaviour to classes and their elements. They provide a way to include both annotations and meta-programming capabilities for class declarations and members.

Decorators are typically used in:

  • Class definitions
  • Properties
  • Methods
  • Accessors
  • Parameters

- Click for setup instructions -

Class Example

Decorator outside the Class

  • First we are console logging our newly created instance of a Cat (Class); it's features (properties) are simply that it's fur is long, and it's eyes are green.
  • We want to create a new Cat with a collar on, so we'll need to use a decorator.
  • To ready the decorator, we use the '@' and the name only, as the decorator will execute at runtime: Therefore, we'll place @Collar above the Cat Class definition.
  • When we compile the typescript and run the script again, our newly created Cat now has a collar property.
  • In summary: Every instance of a Cat will now have a collar by default as the decorator resides on the class defintion.

Cat Collar Decorator

Method Example

Decorator inside the Class

  • In this example, our add method from the Calculator class is decorated with the @log function, so when we run our script, a log will display for the method name and arguments, in addition to the result.
  • We want to be able to use that log feature on the subtraction method that is called, so we'll assign @log above the subtraction method.
  • After compiling and re-running the script, observe we now get the log trigger for both methods we've decorated.
  • In summary: As these decorators can sit above any method; this allows for flexibility without having to edit the original methods within the class itself.

Calculator Operator Log Decorator

Summary

Decorators in TypeScript are an experimental feature. They provide a powerful way to modify or enhance classes and their members, but it is important to note that the implementation may change in future versions.