Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript interface permutations

Tags:

typescript

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.

like image 384
Dmytro Filipenko Avatar asked Sep 19 '25 22:09

Dmytro Filipenko


1 Answers

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.

like image 157
Oleg Vaskevich Avatar answered Sep 22 '25 11:09

Oleg Vaskevich