TypeScript class decorators - add class method

岁酱吖の 提交于 2019-12-08 23:30:54

问题


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?


回答1:


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()



来源:https://stackoverflow.com/questions/36512151/typescript-class-decorators-add-class-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!