DEV Community

alansiqueira
alansiqueira

Posted on

2 3

Typescript Decorators and you

Typescript's decorators help us create elegant code. Although tempting, we should refrain from overusing them in our code. We will mostly use Typescript decorators on

class definitions
properties
methods
accessors
parameters

Before we start, the best way to see it in action is to compare TypeORM Entity method with and without the use of decorators. Below you'll find how you'd declare an Entity with TypeORM without decorators:

module.exports = {
    name: "Post",
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: true
        },
        title: {
            type: "varchar"
        },
        text: {
            type: "text"
        }
    }

};

And now, the same Entity connection but with the use of decorators:

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class Post {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    title: string;

    @Column()
    text: string;

}

In the examples above, Typeorm library uses the decorator function to shorten the process of mapping a database table for you. Of course you still can do it with plain ES6/ES5 Javascript, but if you'll extend your typescript application to its fullest potential you should enable the usage of decorators.

We can enable it by editing our tsconfig.json:

{
    "compilerOptions": {
        "target": "ES5",
        "experimentalDecorators": true
    }
}

Decorator Factories:

Decorator factories are used to customize how they are applied to a declaration. They are basically a function with an expression that will be called upon running the decorator:

function Freeze(value: string) { // Factory
    return function (target) { // Decorator
        target.frozen = true;
    }
}

/*
* Calling the decorator
*/

@Freeze()
const IceCubes = () => { }

Class Decorators:

Declared right before a class, this kind of decorator is applied to the constructor of the class and can be used to replace a definition or modify it.

Reference video

Official Documentation

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay