【问题标题】:Require decorator in interface implementation在接口实现中需要装饰器
【发布时间】:2021-04-29 16:45:06
【问题描述】:

我希望强制 typescript 接口的某些成员在其实现中需要装饰器。

这是我的示例界面:

export interface InjectComponentDef<TComponent> {
  // TODO is it possible to make this only allow properties decorated with @Input()
  inputs: Partial<TComponent>, // & { @Input() [key: string]: any } my attempt to enforce decorator, invalid syntax 
  //... 
};

我的目标是提供以下课程,我想禁止 notAnInput 属性包含在 InjectComponentDef.inputs 实现中

export class MyComponent {
   public @Input() isAnInput: string;
   public notAnInput: string;
}
...
let x:InputComponentDef<MyComponent>=
{
    inputs: {
        isAnInput:'all good',
        notAnInput:'no good', // I want this to throw a compile time error because it is not decorated with @Input
    }
}

有没有办法在 编译时在 typescript 中完成此任务?

【问题讨论】:

    标签: typescript interface decorator


    【解决方案1】:

    来自the TS docs

    类装饰器的表达式将在运行时作为函数调用,装饰类的构造函数作为其唯一参数。

    还有:

    [它们] 评估为将在运行时调用的函数,其中包含有关修饰声明的信息。

    这听起来像是装饰器根本不应该在编译时使用。 因此,即使它使用一些变通方法有效,从设计角度来看,该方法也可能不正确。

    归根结底,您的用例看起来像是在编译时无法真正捕捉到的东西。

    要考虑的一件事:为什么需要强制执行@Input()?考虑一些为 notAnInput 本身设置数据的子对象,根据您的用例,这可能完全有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 2020-11-02
      • 2015-07-23
      • 2012-10-26
      • 1970-01-01
      • 2016-04-02
      相关资源
      最近更新 更多