TypeScript类修饰器-添加类方法 [英] TypeScript class decorators - add class method

查看:252
本文介绍了TypeScript类修饰器-添加类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

并使用它:

@Entity
class Project {
    //
}

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

我有此控制台日志:

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

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

This code correctly worked, but tsc return error:

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

如何解决此错误?

推荐答案

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

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

因此,您要么不使用装饰器来扩展类,要么在适当时使用带有声明合并的接口来扩展类型声明.或使用类型断言(但丢失类型检查):(<any>project).test()

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

这篇关于TypeScript类修饰器-添加类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆