DEV Community


Posted on

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

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";

export class Post {

    id: number;

    title: string;

    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

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

Top comments (0)