【问题标题】:How to add a new property or method to a class using decorator?如何使用装饰器向类添加新属性或方法?
【发布时间】:2018-05-25 12:44:53
【问题描述】:

基本上是same question as this。但还有一些要求。

  1. 如何使用 property 装饰器而不是 class 装饰器向类添加新属性/方法?
  2. 关键是 - 如何以类型安全的方式自动执行此操作? TypeScript 可以支持推断添加的密钥吗?在earlier example 中,我们必须手动添加类型信息。 TypeScript 可以推断吗?

一个例子:

class HeaderComponent extends Vue {

    // @Stream$ should add key teanantId$ to class?
    @Stream$((store) => store.urlState.tenantId)
    public tenantId: number;
}

它应该是这样工作的:

const a = new HeaderComponent();

// works
a.tenant;

// CAN THIS WORK?
a.tenantId$;

【问题讨论】:

    标签: typescript decorator


    【解决方案1】:

    TypeScript 中的类装饰器突变当前为 is not supported

    装饰类需要合并声明来明确定义新属性:

    interface HeaderComponent {
        tenantId$: Observable<number>;
    }
    class HeaderComponent extends Vue {
        @Stream$((store) => store.urlState.tenantId)
        public tenantId: number;
    }
    

    由于tenantId$属性名是运行时计算的结果,以后不可能推断出它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 2023-03-10
      • 2019-11-02
      • 2022-10-13
      • 2021-03-11
      相关资源
      最近更新 更多