AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Typescript Decorators: How does this extension work?

PARTAGEZ

Typescript Decorators (Decorators Typecript) allow additional functions to add objects to objects, without having to modify the source code. They can be applied to classes, methods, properties, access functions and parameters, and access annotations and metadata.

Typescript Decorators: what is it and what is it for?

The principle of the Typescript Decorators is fundamentally nothing new. There are similar concepts in other programming languages ​​such as C#attributes, python decorators or java annotations. It is a question of being able to extend the functions of an object without modifying the source code. Typescript also has been working for a long time according to this approach. Certainly, most browsers do not support (yet) types Script Decorators, but it is still interesting to try this method and its possibilities. From the TypeScript 5.0 version, their use has been considerably simplified.

Typescript Decorators are used to add additional annotations and metadata to standard classes and elements. In addition to classes, it is possible to modify the methods, properties, access methods as well as parameters. These can be checked and their values ​​consulted. This is one of the large differences between the types of Script Decorators and their equivalent for JavaScript.

Managed NextCloud of Ionos Cloud

Work as a team in your own cloud

  • Data security
  • Integrated collaboration tools
  • Accommodation in European data centers

Syntax and functioning of decorators

By adding types script for an object, you call a function that can be performed Without modification of the source code. You thus increase the functionality while keeping a clear code. The basic syntax is as follows:

@nomDuDecorateur

Typescript

You can create this function with two or three settings. The syntax of the function with three parameters takes the following form:

function decoratorFonction(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log(`Decorating ${propertyKey} of class ${target.constructor.name}`);
}
class MyClass {
    @decoratorFonction
    myMethod() {
    }
}

Typescript

The different elements of the Decorators type type are as follows:

  • target : designates the object to which the decorator has been awarded
  • propertyKey : is a thong containing the name of the class to which a decorator has been attributed; These may, among other things, methods or properties
  • descriptor : allows additional information to be stored on the object on which the decorator is applied; possible properties are value,, writable,, enumerable Or configurable.

Here, below, the syntax of the Typecotors type type has two parameters:

function decoratorFonction(target: any) {
    console.log(`Decorating ${target.name}`);
}
@decoratorFonction
class MyClass {
}

Typescript

In this case, the Typescript Decorators have been applied to a class.

The different types of decorators

There are different types of Typecrators types. We present them in more detail below, with their respective particularities:

  • Class Decorators
  • Method Decorators
  • Property Decorators
  • Accessor Decorators
  • Decorators parameter

Typescript Decorators for classes

Typescript Decorators make it possible to adapt the characteristics of a class and modify its manufacturer, methods or properties. As soon as you « decorate » the class with a function, you receive the manufacturer as the first parameter. Here is an example of code dealing with a list of customers. It has some private and public properties:

class Client {
    private static userType: string = "Generic";
    private _email: string;
    public nomduclient: string;
    public rue: string = "";
    public lieuderesidence: string = "";
    public pays: string = "";
    constructor(nomduclient: string, email: string) {
        this.nomduclient = nomduclient;
        this._email = email;
    }
    static get userType() {
        return Client.userType;
    }
    get email() {
        return this._email;
    }
    set email(nouvelemail: string) {
        this._email = nouvelemail;
    }
    adresse(): string {
        return `${this.rue}\n${this.lieuderesidence}\n${this.pays}`;
    }
}
const p = new Client("clientexemple", "name@exemple.com");
p.rue = "6 rue de Drulingen";
p.lieuderesidence = "Strasbourg";

Typescript

In the next step, we use the Typescript Decorators to add other functions that do not modify the source code afterwards. We add the decorator @frozen For the « client » class. This function ensures that objects cannot be changed later. For some properties, we use @required To explicitly indicate the entry. We also use @enumerable For enumerations and @deprecated For obsolete entries. Let us first see together the definition of decorators:

function frozen(constructor: Function) {
    Object.freeze(constructor);
    Object.freeze(constructor.prototype);
}
function required(target: any, propertyKey: string) {
}
function enumerable(value: boolean) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        descriptor.enumerable = value;
    };
}
function deprecated(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.warn(`The method ${propertyKey} is deprecated.`);
}

Typescript

After using the Typescript Decorators, the code resulting in the following syntax:

@frozen
class Client {
    private static userType: string = "Generic";
    @required
    private _email: string;
    @required
    public nomduclient: string;
    public rue: string = "";
    public lieuderesidence: string = "";
    public pays: string = "";
    constructor(nomduclient: string, email: string) {
        this. nomduclient = nomduclient;
        this._email = email;
    }
    @enumerable(false)
    static get userType() {
        return Client.userType;
    }
    get email() {
        return this._email;
    }
    set email(nouvelemail: string) {
        this._email = nouvelemail;
    }
    @deprecated
    adresse(): string {
        return `${this.rue}\n${this.lieuderesidence}\n${this.pays}`;
    }
}
const p = new Client("clientexemple", "nom@exemple.com");
p.rue = "6 rue de Drulingen";
p.lieuderesidence = "Strasbourg";

Typescript

Typescript Decorators for methods

The use of Typescript Decorators is also possible for methodsexcept for declaration files,overloading (overload of function) or « Declare » class. In the following example, we use @enumerable as a decorator for the method getName in the « person » class:

const enumerable = (value: boolean) => {
    return (target: any, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {
        propertyDescriptor.enumerable = value;
    }
}
class Personne {
    prenom: string = "Julie"
    nom: string = "Rault"
    @enumerable(true)
    getName () {
        return `${this.prenom} ${this.nom}`;
    }
}

Typescript

Typescript Decorators for properties

Typescript Decorators for the properties of a class (Property Decorators) have two parameters: the manufacturer's function of the class and the name of the property. In the following example, we use the decorator to display the name of a property (here the customer name):

const printPropertyName = (target: any, propertyName: string) => {
    console.log(propertyName);
};
class Client {
    @printPropertyName
    name: string = "Julie";
}

Typescript

Typescript Decorators for access functions

THE Accessor Decorators work according to a principle very similar to that of the Property Decorators. Unlike these, they have a third parameter in addition. In our example, it is Property Descriptor for a customer. By indicating a value with the Decorator accessor, it becomes the new Property Descriptor. In the following code, the Boolean (« True » or « False ») value of enumerable is thus modified.

const enumerable = (value: boolean) => {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        descriptor.enumerable = value;
    }
}

Typescript

Here's how to apply the decorator:

class Client {
    prenom: string = "Julie";
    nom: string = "Rault";
    @enumerable(true)
    get name() {
        return `${this.prenom} ${this.nom}`;
    }
}

Typescript

Typescript Decorators for settings

Type -type types of type Decorator parameter Also have three parameters: the class manufacturer's function, the name of the method and in addition an index designation of the parameter. However, the parameter in itself cannot be modified, so that this decorator can be used Only for verification. If you want, for example, consult the index, do it with this code:

function print(target: Object, propertyKey: string, parameterIndex: number) {
    console.log(`Decorating param ${parameterIndex} from ${propertyKey}`);
}

Typescript

If you then apply the decorator setting, the code is as follows:

class Exemple {
    testMethod(param0: any, @print param1: any) {}
}

Typescript

Advice

Ideal for static websites and applications: With Deploy Now of Ionos, you benefit from a simulation environment (staging) Simple, a quick installation and perfectly harmonized workflows. Find the model best suited to your needs!

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact