Table of Contents Preface typescript angular

Decorators

Dec­o­ra­tors were in­tro­duced in Type­Script 1.5[1] and are also por­posed for ES­2016 by Yehuda Katz.[2] The pro­posal spec­i­fies a dec­o­ra­tor as a func­tion that makes it pos­si­ble to an­no­tate and mod­ify classes and their prop­er­ties at de­sign time.

Im­ple­ment­ing the dec­o­ra­tor pat­tern is al­ready pos­si­ble in cur­rent JavaScript ver­sions by pass­ing an ob­ject or func­tion to a dec­o­ra­tor method. But the pro­posed syn­tax uses @ as a pre­fix for the dec­o­ra­tor func­tion which would make ap­ply­ing dec­o­ra­tors very de­clar­a­tive.

A look at Type­Scrip­t’s core.d.ts[3] show that there are cur­rently for dif­fer­ent types of dec­o­ra­tors:

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;

You can ap­ply a dec­o­ra­tor by prepend­ing it to what­ever you want to dec­o­rate. A sim­ple ex­am­ple is to make a class method read­only.[4] The fol­low­ing readonly func­tion im­ple­ments this by set­ting the writable prop­erty of the method to false. The sec­ond code snip­pet shows how the dec­o­ra­tor then is ap­plied to the sayHello method.

export readonly( target, key, descriptor ) {
    descriptor.writable = false;
    return descriptor;
}
import { readonly } from 'util/decorators';

class Person {
    public name:string;

    construcotr( name:string ) {
        this.name = name;
    }

    @readonly
    sayHello() {
        return `{Hello, my name is ${this.name}}!`;
    }
}

The spec does not yet in­clude a dec­o­ra­tor for func­tions, be­cause hoist­ing makes it not pos­si­ble. Type­Script con­forms the cur­rent dec­o­ra­tor draft.[5] Reg­u­lar func­tions can be dec­o­rated by wrap­ping the dec­o­ra­tor ar­round them, like let decorateFn = decorator(myFunction);.


  1. What's new in TypeScript

  2. Yehuda Katz - JavaScript Decorators

  3. TypeScript core.d.ts

  4. Addy Osmani - Exploring ES7 Decorators

  5. TypeScript Issue #2249 - Decorators