【问题标题】:TypeScript class decorators - add class methodTypeScript 类装饰器 - 添加类方法
【发布时间】:2016-04-09 02:46:43
【问题描述】:

如何使用 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;
}

并使用它:

@Entity
class Project {
    //
}

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

我有这个控制台日志:

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

此代码正常运行,但 tsc 返回错误:

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

如何解决这个错误?

【问题讨论】:

    标签: typescript annotations decorator


    【解决方案1】:

    据我所知,这是不可能的。这里有关于这个问题的讨论:issue

    因此,您要么不使用装饰器来扩展类,要么在适当的情况下使用带有声明合并的接口来扩展类型声明。或者使用类型断言(但失去类型检查):(&lt;any&gt;project).test()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2014-01-14
      • 2020-01-11
      • 2022-10-13
      • 1970-01-01
      • 2021-03-11
      相关资源
      最近更新 更多