Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Enabling Decorators
3.
Types of TypeScript Decorators
4.
Class Decorators
5.
Method Decorators
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Typescript Decorator Class methods

Author Parth
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction 

Let us assume that a gift box must be gifted to a particular individual. The box’s packaging is flawless. However, it can be made even better. We can do so by attaching a readymade ribbon bow to the box. When attached to the box, this bow now increases the appeal of the gift without much effort. This readymade bow is an example of a decorator. 
A TypeScript decorator is a special type of declaration that can be attached to a class, method, property, or parameter to increase its functionality without complex syntaxes.TypeScript decorators are fundamental functions that can be attached to the exoskeleton of a class to provide additional functionality.
To attach a Typescript decorator, we simply need to use the @expression syntax. Here expression means the name of the function that has been declared already. 

Enabling Decorators

Currently, Typescript decorators are a stage-2 proposal for Javascript and thus subject to changes via patches and updates. The experimentalDecorators compiler option must be enabled via command line or in the tsconfig.json file to use Typescript decorators.

Command Line:

tsc --target ES5 --experimentalDecorators

Tsconfig.json:

{
  "compilerOptions": {
    "target": "ES5",
    "experimentalDecorators": true
  }
}
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Types of TypeScript Decorators

Decorators can extend the functionality of classes, methods, properties, accessors, and parameters. Typescript uses the following Decorator types to accomplish this :

  1. Class Decorators
  2. Method Decorators
  3. Accessor Decorators
  4. Property Decorators
  5. Parameter Decorators

Class Decorators

The class decorators are responsible for decorating a class or, in other words increasing the functionality of a class by wrapping a decorator over it.

Function decorator (constructor:Function) {
console.log(“logging data…”);
console.log(constructor);
}
@decorator
Class Student {
name=”Manas”;
constructor( ) {
console.log(‘Creating Object…’);
                         }
}
const student=new Student();
console.log(student);

Output

logging data…
Class Student {
constructor( ) {
this.name=”Manas”;
console.log(‘Creating Object…’);
                         }
}
Creating Object…
Student{name:”Manas”}

The class decorator function takes the class constructor function as its argument to increase its functionality.

Also, the TypeScript decorator function was initialized even before the new class was instantiated. 

Even if we were not to create a new class object, the TypeScript decorator function would still execute.

Function decorator (constructor:Function) {
console.log(“logging data…”);
console.log(constructor);
}
@decorator
Class Student {
name=”Manas”;
constructor( ) {
console.log(‘Creating Object…’);
                         }
}
//const student=new Student();
//console.log(student);

Output:

logging data…
Class Student {
constructor( ) {
this.name=”Manas”;
console.log(‘Creating Object…’);
                         }
}

Method Decorators

The method decorator is attached before a method is declared and has three arguments to help observe, replace or modify the method declaration. These arguments are:

  1. Target: Usually points to the prototype of a class or its constructor function
  2. Property key: Points to the name of the method that is attached to it.
  3. Descriptor: Acts as a Property Descriptor of the method.

The Property Descriptor is defined as:

interface PropertyDescriptor {
    configurable?: boolean;
    enumerable?: boolean;
    value?: any;
    writable?: boolean;
    get?(): any;
    set?(v: any): void;
}

A practical example of a method decorator is as follows

function methodDecorator(value: string) {
  return function (target: any,propertyKey: string,descriptor: PropertyDescriptor) {
   console.log(target);
   console.log(propertyKey);
   console.log(descriptor);
    console.log(value)
  };
}
class Greeting {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  @methodDecorator("Welcome")
  greet() {
    return "Hello, " + this.greeting; 
  }
}
let a =new Greeting("Parth");
console.log(a.greet())

Output:

Greeting: {} 
"greet" 
{
  "writable": true,
  "enumerable": false,
  "configurable": true
} 
"Welcome" 
 "Hello, Parth" 

FAQs

  1. How do I create a decorator in TypeScript?
    To create a decorator in Typescript, a function with an argument set as the constructor function of the target class has to be created. Then, using a special syntax @expression where expression is the function name is to be placed before the target class or method.
     
  2. How many decorators are there in TypeScript?
    Typescript  supports five types of decorators:
  • Class Decorators
  • Method Decorators
  • Accessor Decorators
  • Property Decorators
  • Parameter Decorators

 

Read Also -  Difference between argument and parameter

Key Takeaways

We learned about Typescript's Decorators, Class, and Method Decorators and how their syntaxes are used from this article. We also learned how TypeScript decorators improve code readability and help introduce functions in classes in the form of TypeScript decorators. We looked into how the property descriptor argument can observe, replace and modify a particular class method. However, this isn't enough, as there is always much more to explore and learn about this vast field of Web Development. To know more about Typescript and its intricacies, check out the articles on Typescript or enroll in our highly curated Web Development course.

Previous article
Decorators in Typescript
Next article
Date Object in Typescript
Live masterclass