装饰器(Decorator)是一种编程模式(Design Pattern),在某些情况下可以用来替代继承(inheritance),以更灵活、轻量的方式重用代码。

装饰器其实就是 Wrapper 的一种应用,举例来说:

class C {
    A() {
        console.log("A");
    }

    B() {
        console.log("B");
    }
}

class D {
    c: C;

    constructor(c: C) {
        this.c = c;
    }

    A() {
        this.c.A();

        console.log("Z");
    }
}

以上程序中,D 的对象实体可以包裹一个 C 的对象实体,并且扩充 C 的对象实体的 A 方法的功能(原本只输出 A,变成输出 A 和 Z)。此类别 D 就是一个装饰器,它的用法如下:

const d = new D(new C());

d.A();

TypeScript 的装饰器

TypeScript 内置装饰器的支持,可以用比较易读的语法来套用装饰器设计模式。不过这个功能还在实验中,如果要使用,必须要在 tsconfig.json 文件中的 compilerOptions 字段内,加上 experimentalDecorators 字段,并将字段值设为 true。

装饰器

TypeScript 的装饰器为一个函数,这个函数的类型会根据其要装饰的对象类型而有所不同。以下会依照装饰器的装饰对象来介绍装饰器。

类别装饰器

类别装饰器的函数类型为 (target: any) => void,target 参数即为装饰对象的构造器函数(即类别本身)。

例如以下函数,就是一个类别装饰器:

function d(target: any) {
    console.log('Class Decorator');
}

我们可以用小老鼠符号 @ 再接上装饰器名称(即函数名称或保存函数的变量、参数、常数的名称)或是路径,来套用该装饰器。

类别装饰器的 @ 要放置于 class 关键字之前。如果也有使用 export 关键字,要放在 export 关键字之前。

例如:

function d(target: any) {
    console.log("Class Decorator");
}

@d
class C {

}

编译以上程序并立刻运行的话,会输出 Class Decorator 文字。

方法装饰器

若 TypeScript 的编译目标为 ES5 或是以上的版本,方法装饰器的函数类型为 (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void 或 (target: any, propertyKey: string) => void。target 参数保存要用来装饰的类别构造器(装饰静态方法时),或是该类别的原型(装饰对象方法时)。propertyKey 参数保存要用来装饰的方法名称,descriptor 参数则是保存属性的「选项」(例如在先前章节有稍微提到的 enumerable)。

例如以下函数,就是一个方法装饰器:

function d(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("Method Decorator");
}

若 TypeScript 的编译目标为 ES3,则方法装饰器的函数类型只能为 (target: any, propertyKey: string) => void。

方法装饰器的 @ 要放置于方法名称之前。如果也有使用 private、protected、set、get 关键字,要放在它们之前。

例如:

function d(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("Method Decorator");
}

class C {
    @d
    m() {

    }
}

编译以上程序并立刻运行的话,会输出 Method Decorator 文字。

descriptor 参数的 value 字段即为方法本身。例如上面看过的这个例子:

class C {
    A() {
        console.log("A");
    }

    B() {
        console.log("B");
    }
}

class D {
    c: C;

    constructor(c: C) {
        this.c = c;
    }

    A() {
        this.c.A();

        console.log("Z");
    }
}

可以将「方法运行完之后输出一个 Z 文字」的功能做成 TypeScript 的装饰器,将程序改写如下:

function Z(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function () {
        originalMethod.call(this);

        console.log("Z");
    };
}

class C {
    @Z
    A() {
        console.log("A");
    }

    B() {
        console.log("B");
    }
}

这边要注意的是,若要在 descriptor 参数的 value 字段中调用原本的方法,最好用方法提供的 call 函数并代入 this 作为参数来调用,这样才可以确保在原先方法中使用到的 this 关键字会是该对象本身的参考。

参数装饰器

参数装饰器的函数类型为 (target: any, propertyKey: string, parameterIndex: number) => void。target 参数保存要用来装饰的类别构造器(装饰静态方法的参数或是构造器的参数时),或是该类别的原型(装饰对象方法的参数时)。propertyKey 参数保存要用来装饰的参数所在的方法名称。parameterIndex 保存要用来装饰的参数序数(从 0 开始数)。

例如以下函数,就是一个参数装饰器:

function d(target: any, propertyKey: string, parameterIndex: number) {
    console.log("Parameter Decorator");
}

参数装饰器的 @ 要放置于参数名称之前。如果也有使用 public 关键字,要放在它之前。

例如:

function d(target: any, propertyKey: string, parameterIndex: number) {
    console.log("Parameter Decorator");
}

class C {
    constructor(@d public a: number) {

    }

    m(@d a: number) {
        this.a = a;
    }
}

编译以上程序并立刻运行的话,会输出两行 Parameter Decorator 文字。

字段装饰器

字段装饰器的函数类型为 (target: any, propertyKey: string) => void。target 参数保存要用来装饰的类别构造器(装饰静态字段时),或是该类别的原型(装饰对象字段时)。propertyKey 参数保存要用来装饰的字段名称。

例如以下函数,就是一个字段装饰器:

function d(target: any, propertyKey: string) {
    console.log("Field Decorator");
}

字段装饰器的 @ 要放置于字段名称之前。如果也有使用 private、protected、readonly 关键字,要放在它们之前。

例如:

function d(target: any, propertyKey: string) {
    console.log("Field Decorator");
}

class C {
    @d
    n = 0;
}

编译以上程序并立刻运行的话,会输出 Field Decorator 文字。

装饰器工厂(Decorator Factory)

我们可以再撰写一层拥有自订参数的函数,用它来产生装饰器,这个函数即称为「装饰器工厂」。装饰器工厂函数的类型并没有限制,但它的回传值类型必须要是上面提到的那些装饰器的类型。

例如以下函数,就是一个类别装饰器工厂:

function f() {
    console.log("Class Decorator Factory");

    return (target: any) => {
        console.log("Class Decorator");
    };
}

我们可以用小老鼠符号 @ 接上装饰器工厂名称或是路径,再用小括号 () 传入要代进装饰器工厂的参数,来套用该装饰器工厂。

例如:

function f() {
    console.log("Class Decorator Factory");

    return (target: any) => {
        console.log("Class Decorator");
    };
}

@f()
class C {

}

编译以上程序并立刻运行的话,会输出 Class Decorator Factory 和 Class Decorator 文字。

再举个例子,利用装饰器工厂,我们可以替方法快速加上 Log 功能,来记录它们何时被调用的。代码如下:

function log(tag: string) {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        const originalMethod = descriptor.value;

        descriptor.value = function () {
            console.log(tag);

            originalMethod.call(this);
        };
    };
}


class C {
    @log("m1")
    m1() {

    }

    @log("m2")
    m2() {

    }

    @log("m3")
    m3() {

    }
}

装饰器的顺序

不同对象的装饰器(或装饰器工厂)的套用顺序是从上到下,从内到外,从右到左。相同对象的装饰器的套用顺序是从下到上(或者说从右到左)。例如:

function cd1(target: any) {
    console.log("Class Decorator 1");
}

function cd2(target: any) {
    console.log("Class Decorator 2");
}

function md1(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("Method Decorator 1");
}

function md2(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("Method Decorator 2");
}

function md3(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("Method Decorator 3");
}

function pd1(target: any, propertyKey: string, parameterIndex: number) {
    console.log("Parameter Decorator 1");
}

function pd2(target: any, propertyKey: string, parameterIndex: number) {
    console.log("Parameter Decorator 2");
}

function fd1(target: any, propertyKey: string) {
    console.log("Field Decorator 1");
}

function fd2(target: any, propertyKey: string) {
    console.log("Field Decorator 2");
}

function fd3(target: any, propertyKey: string) {
    console.log("Field Decorator 3");
}

function fd4(target: any, propertyKey: string) {
    console.log("Field Decorator 4");
}

@cd1
class A {
    @fd1
    @fd2
    m = 0;

    @fd3
    n = 0;
}

@cd2
class B {
    @md1
    @md2
    run() {

    }

    @fd4
    f = 0;

    @md3
    compute(@pd1 x: number, @pd2 y: number) {

    }
}

以上程序的输出结果如下:

Field Decorator 2
Field Decorator 1
Field Decorator 3
Class Decorator 1
Method Decorator 2
Method Decorator 1
Field Decorator 4
Parameter Decorator 2
Parameter Decorator 1
Method Decorator 3
Class Decorator 2

总结

在这个章节中我们学会了 TypeScript 的装饰器用法,利用装饰器我们可以省下撰写很多重复代码的功夫。最后再举个模拟 HTTP 路由程序的例子,如下:

type method = "get" | "post";

const routes: {
    [_: string]: {
        get?: Function,
        post?: Function
    }
} = {};

function resolve(method: method, path: string, ...data: any[]): any {
    if (routes.hasOwnProperty(path)) {
        const handlers = routes[path];

        const handler = handlers[method];

        if (typeof handler === "function") {
            switch (method) {
                case "get":
                    console.log(handler());
                    break;
                case "post":
                    console.log(handler(...data));
                    break;
            }
        } else {
            throw Error(`The path \`${path}\` has no handler for the \`${method}\` method.`);
        }
    } else {
        throw Error(`The path \`${path}\` is undefined.`);
    }
}

function get(path: string) {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        if (!routes.hasOwnProperty(path)) {
            routes[path] = {};
        }

        routes[path]["get"] = descriptor.value;
    };
}

function post(path: string) {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        if (!routes.hasOwnProperty(path)) {
            routes[path] = {};
        }

        routes[path]["post"] = descriptor.value;
    };
}

class RouteClass {
    @get("/a")
    @post("/a")
    someGetMethod() {
        return "Hello, world!";
    }

    @post("/b")
    somePostMethod(x: number, y: number) {
        return x + y;
    }
}

resolve("get", "/a");
resolve("post", "/a");
resolve("post", "/b", 1, 2);

以上程序的输出结果如下:

Hello, world!
Hello, world!
3

这个系列的文章就到这里为止了,对于习惯使用「静态类型」的编程语言的开发者来说,TypeScript 无非是开发「动态类型」的 JavaScript 程序的利器!