Typescript装饰器问题

在typescript中用装饰器,对某个class上增加一些方法。

//Decorator
export default function eventDecorator(target: EventEmitterType) {
    target.prototype.on = __event.on.bind(__event)
    target.prototype.off = __event.off.bind(__event)
    target.prototype.remove = __event.remove.bind(__event)
    target.prototype.Events = __event.Events
    target.prototype.emit = function(
        eventName: string,
        ...params: Array<string>
    ) {
        __event.emit.call(__event, eventName, this, ...params)
    }
}

//class
@eventDecorator
class Test {
    constructor() {
        let _this = this as any
        console.log(111111111)
        _this.on('aa', this.callback)
        _this.emit('aa', this)
    }
    callback() {
        console.log(this)
    }
}

new Test()

这个时候直接调用this.on IDE无法识别装饰器方法,改怎么写,不用extends

阅读 4.2k
1 个回答

http://www.typescriptlang.org...

function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    return class extends constructor {
        newProperty = "new property";
        hello = "override";
    }
}

@classDecorator
class Greeter {
    property = "property";
    hello: string;
    constructor(m: string) {
        this.hello = m;
    }
}

console.log(new Greeter("world"));

官方的例子就是用extends实现的,官方就是希望你用extends实现这样的需求,不要总想自己去发明一些奇奇怪怪的东西


https://github.com/Microsoft/...
根据这篇issue,typescript目前虽然可以用上面的方法添加属性方法,但不支持对添加的属性方法进行类型推导,因为typescript里使用装饰器后类的类型是不变的。。。。。
以后能不能修改页不知道

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题