使用TypeScript装饰器扩展ES6类时扩展类型 [英] Extending type when extending an ES6 class with a TypeScript decorator

查看:256
本文介绍了使用TypeScript装饰器扩展ES6类时扩展类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用装饰器( a-la-angular 样式)装饰类,并向其添加方法和属性.

I am trying to decorate a class with a decorator (a-la-angular style), and add methods and properties to it.

这是我的示例修饰类:

@decorator
class Person{

}

这是装饰器:

const decorator = (target)=>{
    return class New_Class extends target {
        myProp:string
    }
}

myProp不是Person的已知属性:

but myProp is not a known property of Person:

person.myProp //Error - myProp does not exist on type Person

如何装饰打字稿类并保留打字完成,打字安全性等?

推荐答案

要补充 jcalz响应,请返回装饰器模式的定义,它不会更改其目标的接口/合同.不只是术语. TypeScript装饰器与Java注释和.NET属性具有相似之处,这与事实相同,即不更改接口:它们只是添加元数据.

To supplement jcalz response, going back to the definition of the Decorator Pattern, it does not change the interface/contracts of its target. It's not just terminology. TypeScript decorators share similarities with Java annotations and .NET attributes which are aligned with the fact not to change the interface: they just add metadata.

Class mixin是解决您的问题的理想人选.但是最好不要在名称中使用"decorator",以免造成混淆.

Class mixin is a good candidate to solve your question. But it's better not to use "decorator" in its name in order to avoid confusion.

这篇关于使用TypeScript装饰器扩展ES6类时扩展类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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