I have the following types:
type Settings = {
enableAdvancedFeature?: boolean;
};
type Options = {
settings?: Settings;
enforceAdvancedOrder?: boolean;
};
I want to make the enforceAdvancedOrder
property a boolean only when settings.enableAdvancedFeature
is true
.
If settings.enableAdvancedFeature
is false
or undefined
, then enforceAdvancedOrder
should be undefined
.
Here’s an example of the desired behavior:
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
};
I tried defining a conditional type for Options but couldn’t figure out how to enforce this dependency between the nested properties.
How can I define the Options type to achieve this behavior while keeping it type-safe? Any suggestions would be greatly appreciated!
2
Answers
Just like that
examples
You can use a union type that allows
enforceAdvancedOrder
to be a boolean ifenableAdvancedFeatures
is set totrue
and otherwise requires thatenforceAdvancedOrder
is undefined.Here’s how:
Here are some samples to verify: