A practical guide to TypeScript decorators
We can all agree that JavaScript is an amazing programming language that allows you to build apps on almost any platform. Although it comes with its own fair share of drawbacks, TypeScript has done a great job of covering up some gaps inherent in JavaScript. Not only does it add type safety to a dynamic language, but it also comes with some cool features that don’t exist yet in JavaScript, such as decorators.

What are decorators?


Although the definition might vary for different programming languages, the reason why decorators exist is pretty much the same across the board. In a nutshell, a decorator is a pattern in programming in which you wrap something to change its behavior.

In JavaScript, this feature is currently at stage two. It’s not yet available in browsers or Node.js, but you can test it out by using compilers like Babel. Having said that, it’s not exactly a brand new thing; several programming languages, such as Python, Java, and C#, adopted this pattern before JavaScript.

Even though JavaScript already has this feature proposed, TypeScript’s decorator feature is different in a few significant ways. Since TypeScript is a strongly typed language, you can access some additional information associated with your data types to do some cool stuff, such as runtime type assertion and dependency injection.

Getting started


Start by creating a blank Node.js project.

$ mkdir typescript-decorators
$ cd typescript decorators
$ npm init -y

Next, install TypeScript as a development dependency.

$ npm install -D typescript @types/node

The @types/node package contains the Node.js type definitions for TypeScript. We need this package to access some Node.js standard libraries.

Add an npm script in the package.json file to compile your TypeScript code.

{
  // ...
  "scripts": {
    "build": "tsc"
  }
}

TypeScript has labeled this feature as experimental. Nonetheless, its stable enough to use in production. In fact, the open source community has been using it for quite a while. 

To activate the feature, you’ll need to make some adjustments to your tsconfig.json file.

{
  "compilerOptions": {
    "target": "ES5",
    "experimentalDecorators": true
  }
}

Create a simple TypeScript file to test it out.

console.log("Hello, world!");

$ npm run build