Hi everyone,
I’m working with the type system and trying to define a type for a table where only one group of related fields is allowed at a time, and all others are disallowed.
The general idea
I want to define a type Props = ...
that enforces rules like:
- If field
A
exists, thenB
,C
,D
, etc. must not exist. - If field
B
exists, thenA
,C
,D
, etc. must not exist. - Some fields like
C
andD
may be allowed together, but not withA
orB
.
I’m looking for the cleanest or most idiomatic way to express this kind of mutual exclusivity
Example use case
Here’s a specific case I’m working on. I have a Props
table where users can define padding values in one of several mutually exclusive ways:
-
Padding
— applies to all sides -
Vertical
— applies to top and bottom -
Horizontal
— applies to left and right -
Top
,Bottom
,Left
,Right
— can be used individually or together
Each field is of type number
. The exclusivity rules are:
- If
Padding
exists, no other padding-related fields are allowed - If
Vertical
exists, thenPadding
,Top
, andBottom
are disallowed - If
Horizontal
exists, thenPadding
,Left
, andRight
are disallowed - If
Left
orRight
exists, thenPadding
andHorizontal
are disallowed - If
Top
orBottom
exists, thenPadding
andVertical
are disallowed
I’d like to define a Props
type that enforces these constraints at the type level.
Has anyone solved something similar, or know the best approach to modeling mutually exclusive field sets like this?