What is the better way to create permutations inside interface? For example, I want to create an interface of properties for a popup
interface Directions {
right: boolean;
bootom: boolean;
} | {
center: boolean;
bootom: boolean;
} | {
left: boolean;
bootom: boolean;
} | {
right: boolean;
middle: boolean;
} | {
center: boolean;
middle: boolean;
} | {
left: boolean;
middle: boolean;
} | {
right: boolean;
top: boolean;
} | {
center: boolean;
top: boolean;
} | {
left: boolean;
top: boolean;
}
My main goal is to allow the only a combination of two properties(one vertical property + one horizontal property)
[right, bottom]
or [center, middle]
but not [right, left, middle]
or [center, left]
. How to make it more general? How to avoid this verbosity?
Thanks.
You can generate type permutations in TypeScript as desired as follows:
type Values<T> = T[keyof T];
type VerticalProperties = 'left' | 'center' | 'right';
type HorizontalProperties = 'top' | 'middle' | 'bottom';
type Directions = Values<Values<{[V in VerticalProperties]: {[H in HorizontalProperties]: {[K in V | H]: boolean}}}>>;
which will generate what you have above.
However, just because you can, doesn't mean you should, because it might be hard to pass around and work with. You might be better off implementing Ryan's suggestion of using an alternative representation or alternatively, just using an enum (with keys Directions.LeftTop
, Directions.LeftMiddle
, etc.), which will be very readable and easy to exhaustively process with a switch-case statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With