Typescript decorator problem

use decorators in typescript to add some methods to a 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()

call this.on IDE directly at this time. The decorator method is not recognized by extends

.
Mar.23,2021

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"));

the official example is implemented in extends. The official hope is that you use extends to achieve such requirements. Don't always try to invent something strange by yourself

< hr >

https://github.com/Microsoft/.
according to this issue,typescript, although it is possible to use the above method to add attribute methods, it does not support type deduction of the added attribute methods, because the type of the class in typescript is unchanged after using the decorator.
can I modify the page later? I don't know

Menu