如何根据另一个嵌套属性有条件地设置 TypeScript 属性?

问题描述 投票:0回答:1

我有以下类型:

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
};

我尝试为选项定义条件类型,但无法弄清楚如何在嵌套属性之间强制执行这种依赖关系。

如何定义选项类型来实现此行为,同时保持类型安全?任何建议将不胜感激!

javascript typescript typescript-typings
1个回答
0
投票

就这样

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
© www.soinside.com 2019 - 2024. All rights reserved.