TypeScript class decorators - add a class method

How to define a property using TypeScript and decorators?

For example, I have this class decorator:

function Entity<TFunction extends Function>(target: TFunction): TFunction {
    Object.defineProperty(target.prototype, 'test', {
        value: function() {
            console.log('test call');
            return 'test result';
        }
    });
    return target;
}

And use it:

@Entity
class Project {
    //
}

let project = new Project();
console.log(project.test());

I have this console log:

test call            entity.ts:5
test result          entity.ts:18

This code worked correctly, but tsc returns an error:

entity.ts(18,21): error TS2339: Property 'test' does not exist on type 'Project'.

How to fix this error?

+4
source share
1 answer

So far, as far as I know, this is impossible. This question is discussed here: issue .

, , , , . ( ): (<any>project).test()

+3

All Articles