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 ownfair share of drawbacks, TypeScript has done a great job of covering up some gaps inherent in JavaScript. Not only does it add typesafety 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 atstage 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 stronglytyped language, you can access some additional information associated with your data types to do some cool stuff, such as runtime typeassertion 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 thepackage.json file to compile your TypeScript code.
{
// ...
"scripts": {
"build": "tsc"
}
}
TypeScript has labeled this feature as experimental. Nonetheless, it’s 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 toyour tsconfig.json file.
What are decorators?
Getting started
$ mkdir typescript-decorators
$ cd typescript decorators
$ npm init -y
$ npm install -D typescript @types/node
{
// ...
"scripts": {
"build": "tsc"
}
}
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
console.log("Hello, world!");
$ npm run build