Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript adding methods with decorator type does not exist

Tags:

typescript

I want to create a decorator that adds a method to a class.

export function Deco() {
  return function<T extends { new (...args: any[]): {} }>(constructor: T) {
    constructor.prototype.someMethod = function() {

    };
  };
}


@Deco()
class Test {

}

The problem is when I'm trying to invoke the added method, I am getting typescript error:

Property someMethod does not exist on type Test.

const test = new Test();

test.someMethod();

How can I solve this issue?

like image 887
undefined Avatar asked Feb 03 '18 17:02

undefined


1 Answers

Decorators can't influence the structure of the type. There is a simple workaround to this. Invoke the decorator with the class, and inside the function create a derived class with the methods you want. The result of the function will the new "decorated" class and it will have all the methods:

export function Deco() {
    return function <T extends { new(...args: any[]): {} }>(constructor: T) {
        return class extends constructor {
            someMethod() {

            }
        }
    };
}


let Test = Deco()(class {
    // Other stuff
});

const test = new Test();
test.someMethod();
like image 118
Titian Cernicova-Dragomir Avatar answered Oct 07 '22 12:10

Titian Cernicova-Dragomir