A Practical Introduction to TypeScript Class Decorators
Published: 2022-08-08 07:33:51

---
title: A Practical Introduction to TypeScript Class Decorators
published: true
date: 2020-02-03 23:00:37 UTC
tags: 
canonical_url: https://hasnode.byrayray.dev/a-practical-introduction-to-typescript-class-decorators-afb996af0763
---

TypeScript is hot and happening at the moment! *I love it*! But a lot of times there come features you don't know, so maybe in your case "Decorator" is one of them. 

This is the first post of a series about TypeScript decorators where I want to give you a practical introduction to them. What is a decorator, which types are there, why would you want to use a decorator and in what kind of situations would you use a decorator.

> *Currently decorator is a stage 2 proposal for JavaScript and is available as an experimental feature of TypeScript.*

*If you want to read more about the specification, which is pretty interesting and well written, check it on the Github repo: [JavaScript Decorators](https://github.com/tc39/proposal-decorators).*

---

![https://images.unsplash.com/photo-1482245294234-b3f2f8d5f1a4?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb](https://images.unsplash.com/photo-1482245294234-b3f2f8d5f1a4?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb)

## What is a Decorator?

What are decorators? Well, think about the meaning of the word "decoration" and you are pretty close.

The TypeScript website they describe it as:

> *A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.*

I would describe it as *A special declaration to add extra features on an existing class declaration, method, accessor, property or parameter*.

### JavaScript Classes

To use a decorator you need to be familiar with JavaScript Classes. Classes are super useful to know! If you don't know what a JavaScript Class is and how they work, I highly recommend checking this video from **Daniel Shiffman** from **The Coding Train**, to have a practical introduction to them. After that, you can follow this post about decorators better.

[https://www.youtube.com/watch?v=T-HGdc8L-7w](https://www.youtube.com/watch?v=T-HGdc8L-7w)

### Angular

If you are using Angular, chances are big you are using decorators like `@Component`, `@NgModule`, `@Input`, `@Output` or `@Inject`. This will help a bit with getting a better understanding of decorators.

## Which decorators are there?

To describe what decorators do in TypeScript we need to dive deeper into each type. There are a few different types of decorators.

1. Class Decorator
2. ~~Property Decorator~~ (will come later)
3. ~~Method Decorator~~ (will come later)
4. ~~Accessor @ Decorator~~ (will come later)
5. ~~Parameter Decorator~~ (will come later)

![https://images.unsplash.com/photo-1552664730-d307ca884978?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb](https://images.unsplash.com/photo-1552664730-d307ca884978?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb)

### Class decorator

Let's start with the class decorator. To visualize that we are gonna build a (*fictive*) piece of the **Lord of the Rings** 🧙‍♂️ game. 

To play the game we need a lot of characters. Some can be the character you play with, some are for the scene around it.

This is the class for a `Character`. It has a `armour`, `height`, `width`, `weight` and `type`. The type is bound to the enum `CharacterType`.

{% gist https://gist.github.com/devbyray/d55e08798106f0ae10ea7bf05af9d60b %}

In the **LOTR** you have a wide variety of characters. We are gonna use the class decorator to make 2 character types, the Hobbit and the Elf.  

Both of the classes extend the `Character` class we defined on top because the Elf and Hobbit both have there owned strengths, weaknesses, and capabilities.

**Hobbit class**

{% gist https://gist.github.com/devbyray/1bd3750c5c2e6f629aa4d6383a655594 %}

Elf class

{% gist https://gist.github.com/devbyray/4f6ffdfed3c99a3ea143471e692344e0 %}

**Hobbit Decorator**

In the Hobbit decorator, we override some properties that are specific if our player is a Hobbit. The same is for the Elf.

A decorator is a function that returns a new constructor which extends the `constructor` of the class. In this constructor we add or overwrite existing properties/methods to the classes we apply the decorator on.

> *Sadly enough we can't get the information from the original constructor to use that information. I learned that after trying for a day! If you know another method, please write it in a comment so I can include it.*

{% gist https://gist.github.com/devbyray/299739f1453e4ed4199ec8e9c341b69c %}

When you want to add the decorator to a class you define it like `@hobbitDec` above the class you want it to be applied to.

{% gist https://gist.github.com/devbyray/9bbde3b2e140e5c674e2eeded3e97d95 %}

When you would console log that in the browser, you should see the information combined with the information from the `PlayerCharacter`.

{% gist https://gist.github.com/devbyray/d7ca3b87d0740972935bd733d34a2283 %}

**Elf decorator**

If we want our player to be an Elf, we do the same thing as for the Hobbit.

{% gist https://gist.github.com/devbyray/e028bad9cf02a3bba3f5bc590165a428 %}

We apply the `@elfDec` on the `PlayerCharacter` class to add the player type information.

{% gist https://gist.github.com/devbyray/3cf5b48b047beb013ebefda24cabff6e %}

Log the information in the console and you see that the correct information is applied.

{% gist https://gist.github.com/devbyray/aea3061a4fc75dc36b94c90cc8a19da0 %}

Now we know how to use a class decorator in TypeScript. If you want to check my whole code of the class decorator? Visit the [TypeScript playground](https://www.typescriptlang.org/play/index.html?experimentalDecorators=true&emitDecoratorMetadata=true#code/GYVwdgxgLglg9mABACzgIzTKARAphAHgBVFcAPKXMAEwGdEBvRMXAdwAoA6bgQwCcA5rQBciHmACeAbQC6ASlEMAvoiUA+dhAS0ofENDh9RROYwBQiS4i1gdKdJiiIAvMzaIAEg6zs5FqwH+ljZ2TKww1FDIADQouDACyFCxrPGJyWJ8ALZwIHyxUBIADrgqrqgYWEEBiNV8uFB5SBAANjy09OSUNPQhuvpQhuY1VuGRyC6IY1HVAchpSZPzCUmzowtOrqkrUGuW-Dl5kwe5fHuIhSWTl7jVSmb3ZqCQsAikLcB4hCRdVHSMbg43E4-CEonE0nkihU6k02n6BiMiBMwysfXewEmLFYiAAoh9fOdquiwhEorFlukUhtYic8gViqVJrgPkSAvVGnxmm0OqQKH9evC9IjUSNphMtmTkOdKYtyhtztt0pMlasRvtsqdjpq8ucbtdGXcHmYzFQQFlEABhZD8HjQXB8IiM0WIAByAHlXbjJgByMAIXA+6LVDzugBCYYAkiRXD6Ko4g9VcQAZABivpZwETj1a7Xo1tt9r4LqKIDQLRgEEyhyRYHNaAdkwAjAAGFsAbmqpfLlbiO1EdayDeLrhbXbLFar4oH9cbo-HPanGxnQ7niDHAW7k4ujNEBb4dsojudrn3h4dTpKnA9XuNZlzvK8lScvx6VptB6LJYnvdlUBXw7Ngu27Tsws4jogABMwG9qq-5gauEEACwblYW69jce4fuex5XKe2FFpeuCcKGEbRiaAR9MKgx8L4LoBLQIAlLRfgBPcOY8vQ+KYq+-xnl+DAwVWdK1uBzZth2Ql9ukAFrq2qGWOhU5SrJEGQQpiBKVMy4IYBrgAJwaVpmHvoWR5EZM-HmYynApqmFFokKAyGHRgnqogjHMYSbF3gA9L5iAAAptBIjYQARR5mAAAvGWBfPenFBSFDpWY2bloT+VZgDwWS4KIOh8DAYACL6wU8KFxbZblPqdjm8KaclEHYkl5UpRFDq+J297aHALTES0cACOwPpFI1ohBg1rV8HIQA) where you can also see how the compiled JavaScript looks.

### **When would you use the class decorator?**

Well, I think it's pretty simple. When you want to overwrite or add a bunch of properties/methods to a class, it can be a good idea to use the class decorator.

**What is the difference between extending a class?**

Maybe your thinking 🤔, you could also extend the `Hobbit` or `Elf` class at the `PlayerCharacter` class. Yes, that also possible!

But the difference, when using a class decorator instead of extending a class, is that when you extend a class, you most of the time will and can manipulate the data from the extended class. In contrast to extending a class, the class decorator will always be on top of the class. So you can't manipulate the data from the decorator inside your class.

So if you use a class decorator, know you can cause some major side effects you didn't think off. 😉

## Thanks

I hope that your now up-to-date with the TypeScript Class Decorator and that you learned how to use it. But also what is not possible with it.

In the next post, I'm gonna show you how to use the TypeScript Property Decorator.

If you have any questions, please post them in the comments 👍.