【发布时间】:2020-11-15 00:36:30
【问题描述】:
考虑以下示例:
interface pluginOptions {
neededProperty: ...neededPropertyType...;
... a bunch of other optional properties ...
}
interface myExtendedPluginOptions extends pluginOptions {
neededProperty?: ...neededPropertyType...;
}
我想要实现的是,我正在使用一个插件,它在初始化时除了要在它接收的选项对象中设置的属性 (neededProperty)。我想围绕该插件编写一个包装器类,它将这个选项对象提供给原始插件,但是当我实例化我的包装器时,它不依赖于选项中存在的对象,而是以不同的方式获取这个值.基本上是这样的:
/** old init */
const plugin = plugin(pluginOptions);
/** new init */
class ExtendedPlugin {
constructor(neededProperty: ...neededPropertyType..., options: myExtendedPluginOptions) {
this.plugin = plugin(jQuery.extend(myExtendedPluginOptions, {
neededProperty: neededProperty
});
}
}
const plugin = new ExtendedPlugin(neededProperty, myExtendedPluginOptions);
我需要这个的原因是,在我们的框架中,我们使用了不同类型的插件,并且希望以某种方式使用所有这些插件统一,以便其他开发人员更容易工作和他们一起。
在打字稿定义中是否有可能:
- 扩展接口没有扩展接口的某些属性?
- 或者至少,以某种方式指定扩展接口中的强制属性,现在在新接口中是可选的
我知道,我可以将旧接口的所有属性复制到新接口类型中,但我不认为这是最佳解决方案,因为它需要不断维护,以防我们更新原始插件,并添加或删除新属性。
在上面的示例中,打字稿抱怨使扩展接口 requiredProperty 成为可选的,其中:
Property 'neededProperty' is optional in type 'myExtendedPluginOptions' but required in 'pluginOptions' ts(2430)
【问题讨论】:
-
正是我想要的,谢谢!如果您将其转换为答案,我也会接受!
标签: typescript