【发布时间】: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