Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cartesian product types

Is it possible to create the type Cartesian such that Cartesian<'a' | 'b' | 'c'> equals the type

'ab' | 'ba' | 'ac' | 'ca' | 'bc' | 'cb'

Partial solution: if we define type Cartesian<T extends string> = `${T}_${T}`; we also get 'aa', 'bb', and 'cc'. Is there a way to remove those? Perhaps using Exclude?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way you can create the required Cartesian type by using the Extract utility type to exclude the undesired combinations. Something like:

type Cartesian<T extends string> = {
  [K1 in T]: {
    [K2 in T]: K1 extends K2 ? never : `${K1}${K2}`;
  }[T];
}[T];

type Result = Cartesian<'a' | 'b' | 'c'>;
// Result: 'ab' | 'ac' | 'ba' | 'bc' | 'ca' | 'cb'

TS plaground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading