请考虑以下示例:
interface pluginOptions {
neededProperty: ...neededPropertyType...;
... a bunch of other optional properties ...
}
interface myExtendedPluginOptions extends pluginOptions {
neededProperty?: ...neededPropertyType...;
}
我要实现的是,我正在使用一个插件,该插件在初始化时会设置一个属性(neededProperty
,但要在其接收的options对象中进行设置。我想围绕该插件编写一个包装器类,它将将该选项对象提供给原始插件,但是当实例化包装器时,与其依赖该对象存在于选项中,它将以另一种方式获取此值。基本上是这样的:
/** 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)
答案 0 :(得分:1)
它是内置实用程序类型Omit<T, K>
。
type myExtendedPluginOptions = Omit<pluginOptions, 'neededProperty'>;
将产生一种与pluginOptions
具有相同属性,但完全排除了neededProperty
的新类型。