【问题标题】:How to delete property from nested objects inside interface?如何从界面内的嵌套对象中删除属性?
【发布时间】:2023-01-25 18:51:25
【问题描述】:

给定以下示例

interface DataProvider {
    type: string;
    // other props
}

interface ApiConfiguration {
    dataProvider: DataProvider;
    // other props
}

interface Configuration {
    api: ApiConfiguration;
    // other props
}

const configuration: Configuration = {
    api: {
        dataProvider: { type: 'http' }
    }
};

此配置将根据模式进行验证。对于给定的测试,我想确保如果缺少 type 字段,将抛出验证错误。

delete configuration.api.dataProvider.type

不可能因为

“删除”运算符的操作数必须是可选的。

因为接口必须有 type 道具。我知道有 Pick 和 Omit,但是为每个测试用例创建自定义接口类型会非常耗时。

目前我正在使用这种方法

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const clonedConfiguration: any = structuredClone(configuration);

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {type: _, ...dataProviderWithoutType} = clonedConfiguration.api.dataProvider;

clonedConfiguration.api.dataProvider = dataProviderWithoutType;

但是有没有更优雅的方法来从嵌套的孩子中删除道具?

【问题讨论】:

  • 我认为正确的方法是使用省略。
  • @MoritzRoessler 但是我必须创建一个包含所有子类型的全新配置类型.. 不是吗?

标签: javascript typescript


【解决方案1】:

您可以使用 Typescript 中的 as 关键字来执行此操作。使用它时,您明确告诉 Typescript 不要担心对象内部的内容。

详情请见this question

interface DataProvider {
    type: string;
    // other props
}

interface ApiConfiguration {
    dataProvider: DataProvider;
    // other props
}

interface Configuration {
    api: ApiConfiguration;
    // other props
}

const configuration: Configuration = {
    api: {
        dataProvider: {} as DataProvider,
    }
};

【讨论】:

  • 为什么要投反对票?该解决方案似乎有效。就我而言,我不得不写as unknown as DataProvider,但当时测试还不错
猜你喜欢
  • 2021-01-30
  • 2021-10-29
  • 2017-06-02
  • 1970-01-01
  • 2016-04-09
  • 2020-10-30
  • 2012-10-25
  • 1970-01-01
  • 2021-07-27
相关资源
最近更新 更多