Reader small image

You're reading from  Mastering TypeScript - Fourth Edition

Product typeBook
Published inApr 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781800564732
Edition4th Edition
Languages
Right arrow
Author (1)
Nathan Rozentals
Nathan Rozentals
author image
Nathan Rozentals

Nathan Rozentals has been writing commercial software for over 30 years, in C, C++, Java and C#. He picked up TypeScript within a week after its initial release in October 2012 and realized how much TypeScript could help when writing JavaScript. He was one of the first people to start blogging about TypeScript, discussing early frameworks such as Backbone, Marionette, ExtJS and AngularJs. He knew he'd hit the mark when Microsoft staff started to reference his blog posts in their CodePlex discussion forums. Nathan's TypeScript solutions now control User Interfaces in IoT devices, run as stand-alone applications for Point-of-Sale solutions, provide complex application configuration web sites, and are used for mission-critical server APIs.
Read more about Nathan Rozentals

Right arrow

Decorators

Decorators in TypeScript provide a way of programmatically tapping into the process of defining a class. Remember that a class definition describes the shape of a class, what properties it has, and what methods it defines. When an instance of a class is created, these properties and methods become available on the class instance. Decorators, however, allow us to inject code into the actual definition of a class, before a class instance has been created. They are similar to attributes in C#, or annotations in Java.

JavaScript decorators are currently only at a draft or stage 2 level, meaning that it may take a while before they are adopted into the JavaScript standard. TypeScript, however, has supported decorators for quite some time, although they are marked as experimental. Decorators have also become popular due to their use within frameworks such as Angular, where they are primarily used for dependency injection, or Vue, where they are used to inject functions into...

Decorator overview

In this section of the chapter, we will take a look at the general setup and syntax of decorators, what we need to do to enable them, and how they are applied to classes. We will also show how multiple decorators can be used at the same time, and then discuss the different types of decorators. Finally, this section will take a look at decorator factories, and how we can pass parameters into decorator functions.

Decorator setup

Decorators are an experimental feature of the TypeScript compiler and are supported in ES5 and above. In order to use decorators, we need to enable a compile option in the tsconfig.json file. This option is named experimentalDecorators, and needs to be set to true, as follows:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "strict": true,
        "experimentalDecorators": true,
        "skipLibCheck": true...

Exploring decorators

In this section of the chapter, we will work through each of the different types of decorators and experiment with the information that is provided by each decorator function. We will then use what we have learned in order to provide examples of some practical applications of decorators.

Class decorators

We know that in order to define a class decorator, we must define a function that has a single parameter, which is of type Function. Let's take a closer look at this parameter, as follows:

function classConstructorDec(constructor: Function) {
    console.log(`constructor : ${constructor}`);
}
@classConstructorDec
class ClassWithConstructor {
    constructor(id: number) { }
}

Here, we have a decorator function named classConstructorDec, which is logging the value of the constructor argument to the console. We have then applied this decorator to a class named ClassWithConstructor. This ClassWithConstructor class has a single constructor function...

Summary

In this chapter, we have explored the use of decorators within TypeScript. We started by setting up our environment to make use of decorators, and then discussed the syntax used to apply decorators. We learned that we can apply decorators to classes, class properties, class methods, and even class parameters. Each of these decorators has its own set of required parameters and parameter types, based on where it is to be used. We then discussed the use of decorators and saw how we can build an audit log trail using method decorators. In the final part of this chapter, we took a look at decorator metadata, and how this metadata provides additional information about our classes at runtime. In the next chapter, we will explore the integration between TypeScript and JavaScript, and how these two languages can co-exist within the same project.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering TypeScript - Fourth Edition
Published in: Apr 2021Publisher: PacktISBN-13: 9781800564732
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Nathan Rozentals

Nathan Rozentals has been writing commercial software for over 30 years, in C, C++, Java and C#. He picked up TypeScript within a week after its initial release in October 2012 and realized how much TypeScript could help when writing JavaScript. He was one of the first people to start blogging about TypeScript, discussing early frameworks such as Backbone, Marionette, ExtJS and AngularJs. He knew he'd hit the mark when Microsoft staff started to reference his blog posts in their CodePlex discussion forums. Nathan's TypeScript solutions now control User Interfaces in IoT devices, run as stand-alone applications for Point-of-Sale solutions, provide complex application configuration web sites, and are used for mission-critical server APIs.
Read more about Nathan Rozentals