TypeScript类装饰器 - 添加类方法

Ale*_*huk 10 annotations decorator typescript

如何使用TypeScript和装饰器定义属性?

例如,我有这个类装饰器:

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

并使用它:

@Entity
class Project {
    //
}

let project = new Project();
console.log(project.test());
Run Code Online (Sandbox Code Playgroud)

我有这个控制台日志:

test call            entity.ts:5
test result          entity.ts:18
Run Code Online (Sandbox Code Playgroud)

此代码正常工作,但tsc返回错误:

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

如何解决这个错误?

Ami*_*mid 7

据我所知,目前这是不可能的.这里有一个关于这个问题的讨论:问题.

所以你要么不使用装饰器来扩展类,也许如果合适的话,使用带有声明合并的接口来扩展类型声明.或者使用类型断言(但是丢失类型检查):(<any>project).test()