born2net born2net - 26 days ago 14
TypeScript Question

How to let TypeScript know of added methods via class / component decorator?

If I am decorating a Component with my own decorator, how do I let TypeScript know that I have added functionality (methods) to that class via

@MyComponentDecorator


@Component({
selector: 'MySelector',
template: 'bar'

})
@MyComponentDecorator
export class MyClass {

constructor(){
this.myNewMethod('foo'); // TypeScript error as transpiler is not aware
}
}
...


regards

Sean

Answer

You can set up an interface with the same name:

interface MyClass {
    myNewMethod(str: string): void;
}

With this:

function MyComponentDecorator(constructor: { new (): MyClass }) {
    constructor.prototype.myNewMethod = function (str: string) {
        console.log(str);
    }
}

interface MyClass {
    myNewMethod(str: string): void;
}

@MyComponentDecorator
class MyClass {
    constructor() {
         this.myNewMethod('foo');
    }
}

(code in playground)

Comments