【问题标题】:Add function via decorator通过装饰器添加功能
【发布时间】:2016-07-05 09:47:56
【问题描述】:

有没有通过装饰器添加功能的有效方法?

装饰者:

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

类:

@testDecorator({})
class Book{

}

用法(在这种情况下是首选)喜欢

Book.test()

typescript 编译结果:

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

用法

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

typescript 编译结果:

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

【问题讨论】:

    标签: javascript typescript decorator


    【解决方案1】:

    那是因为您的 Book 类/实例没有此 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 对象/类没有声明实例/静态方法 test,但它是由装饰器添加的。

    【讨论】:

      猜你喜欢
      • 2010-11-22
      • 1970-01-01
      • 2011-01-30
      • 2021-11-24
      • 1970-01-01
      • 2011-07-29
      • 2011-07-25
      • 2022-01-09
      • 2018-07-30
      相关资源
      最近更新 更多