我有以下类型:
type Settings = {
enableAdvancedFeature?: boolean;
};
type Options = {
settings?: Settings;
enforceAdvancedOrder?: boolean;
};
我想仅当
enforceAdvancedOrder
为 settings.enableAdvancedFeature
时才将 true
属性设置为布尔值。
如果
settings.enableAdvancedFeature
是 false
或 undefined
,那么 enforceAdvancedOrder
应该是 undefined
。
这是所需行为的示例:
const validOption1: Options = {
settings: { enableAdvancedFeature: true },
enforceAdvancedOrder: true,
};
const validOption2: Options = {
settings: { enableAdvancedFeature: false },
enforceAdvancedOrder: undefined, // enforceAdvancedOrder should be undefined
};
const invalidOption: Options = {
settings: { enableAdvancedFeature: false },
enforceAdvancedOrder: true, // This should cause a TypeScript error
};
我尝试为选项定义条件类型,但无法弄清楚如何在嵌套属性之间强制执行这种依赖关系。
如何定义选项类型来实现此行为,同时保持类型安全?任何建议将不胜感激!
就这样
type ConditionalOption =
| { enforceAdvancedOrder?: boolean, settings?: { enableAdvancedFeature?: true } }
| { enforceAdvancedOrder?: undefined, settings?: { enableAdvancedFeature?: false | undefined } }
示例
let a: ConditionalOption = {
settings: {
enableAdvancedFeature: true
},
enforceAdvancedOrder: true
} // okay
let b: ConditionalOption = {
settings: {
enableAdvancedFeature: false
},
enforceAdvancedOrder: true,
} // throws error
let c: ConditionalOption = {
settings: {
enableAdvancedFeature: false
},
enforceAdvancedOrder: undefined
} // okay