【问题标题】:Extending interface and making a variable optional in the extended one扩展接口并在扩展接口中使变量可选
【发布时间】: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);

我需要这个的原因是,在我们的框架中,我们使用了不同类型的插件,并且希望以某种方式使用所有这些插件统一,以便其他开发人员更容易工作和他们一起。

在打字稿定义中是否有可能:

  1. 扩展接口没有扩展接口的某些属性?
  2. 或者至少,以某种方式指定扩展接口中的强制属性,现在在新接口中是可选的

我知道,我可以将旧接口的所有属性复制到新接口类型中,但我不认为这是最佳解决方案,因为它需要不断维护,以防我们更新原始插件,并添加或删除新属性。

在上面的示例中,打字稿抱怨使扩展接口 requiredProperty 成为可选的,其中: Property 'neededProperty' is optional in type 'myExtendedPluginOptions' but required in 'pluginOptions' ts(2430)

【问题讨论】:

标签: typescript


【解决方案1】:

它是一个内置的实用程序类型Omit<T, K>

type myExtendedPluginOptions = Omit<pluginOptions, 'neededProperty'>;

将生成一个新类型,它具有与pluginOptions 相同的属性,但完全排除了neededProperty

【讨论】:

    猜你喜欢
    • 2017-10-21
    • 2015-08-09
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多