Decorators·续1

TypeScript支持为带有装饰器的声明生成元数据。 你需要在命令行或tsconfig.json里启用emitDecoratorMetadata编译器选项。

Command Line:

tsc --target ES5 --experimentalDecorators --emitDecoratorMetadata

tsconfig.json:

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

当启用后,只要reflect-metadata库被引入了,设计阶段添加的类型信息可以在运行时使用。

如下例所示:

import "reflect-metadata";class Point {    x: number;    y: number;}class Line {    private _p0: Point;    private _p1: Point;    @validate    set p0(value: Point) { this._p0 = value; }    get p0() { return this._p0; }    @validate    set p1(value: Point) { this._p1 = value; }    get p1() { return this._p1; }}function validate<​T>(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<​T>) {    let set = descriptor.set;    descriptor.set = function (value: T) {        let type = Reflect.getMetadata("design:type", target, propertyKey);        if (!(value instanceof type)) {            throw new TypeError("Invalid type.");        }        set.call(target, value);    }}

TypeScript编译器可以通过@Reflect.metadata装饰器注入设计阶段的类型信息。 你可以认为它相当于下面的TypeScript:

class Line {    private _p0: Point;    private _p1: Point;    @validate    @Reflect.metadata("design:type", Point)    set p0(value: Point) { this._p0 = value; }    get p0() { return this._p0; }    @validate    @Reflect.metadata("design:type", Point)    set p1(value: Point) { this._p1 = value; }    get p1() { return this._p1; }}

注意  装饰器元数据是个实验性的特性并且可能在以后的版本中发生破坏性的改变(breaking changes)。