我希望强制 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
}
}
有没有什么办法可以在编译时的打字稿中实现这一点?
答案 0 :(得分:1)
来自the TS docs:
<块引用>类装饰器的表达式将在运行时作为函数调用,装饰类的构造函数作为其唯一参数。
还有:
<块引用>[他们] 计算出一个函数,该函数将在运行时调用,并带有有关装饰声明的信息。
这听起来像装饰器根本不打算在编译时使用。 因此,即使它使用一些变通方法工作,从设计的角度来看,这种方法也可能不正确。
最重要的是,您的用例看起来像是在编译时无法真正捕捉到的东西。
需要考虑的一件事:为什么您需要强制执行 @Input()
?考虑一些为 notAnInput
本身设置数据的子对象,这可能完全有效,具体取决于您的用例。