通过装饰器添加功能

Add function via decorator

是否有通过装饰器添加函数的有效方法?

装饰者:

function testDecorator(options){
    return function(target){
        target.test = function() {
            console.log('Zipp Zapp!');
        };
    }
}

Class:

@testDecorator({})
class Book{

}

用法(在本例中首选)如

Book.test()

打字稿编译结果:

Property 'test' does not exist on type 'typeof Book'.

用法喜欢

var b = new Book();
b.test();

打字稿编译结果:

Property 'test' does not exist on type 'Book'

那是因为你的 Book class/instance 没有这个 test 函数的定义。

您可以为 Book.test 版本执行此操作:

function testDecorator(options) {
    return function(target) {
        target.test = function() {
            console.log('Zipp Zapp!');
        };
    }
}

interface BookConstructor {
    new (): Book;
    test(): void;
}

@testDecorator({})
class Book {}

(Book as BookConstructor).test();

(code in playground)

或者 new Book().test 版本:

function testDecorator(options) {
    return function(target) {
        target.prototype.test = function() {
            console.log('Zipp Zapp!');
        };
    }
}

interface Testable {
    test(): void;
}

@testDecorator({})
class Book {}

let b = new Book();
(b as Testable).test();

(code in playground)

这里的主要区别在于我们在做:

target.prototype.test = function() { ... }

而不是:

target.test = function() { ... }

在这两种情况下你都需要转换,因为 Book object/class 没有声明 instance/static 方法 test 但它是由装饰器添加的。