Search code examples
typescriptannotationsdecorator

TypeScript class decorators - add class method


How to define property with 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 correctly worked, but tsc return error:

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

How to fix this error?


Solution

  • Af far as I know for now this is not possible. There is a discussion on this issue here: issue.

    So you either do not use decorators to extend classes, and maybe if appropriate use interfaces with declaration merging to extend type declaration. Or use type assertion (but loosing type checks): (<any>project).test()