0

I have the following union:

type Letter = 'a' | 'b' | 'c' | 'd' | 'e'

I want to allow for permutations of 1-3 letters using a Template Literal Type:

type Variation = Letter | `${Letter}-${Letter}` | `${Letter}-${Letter}-${Letter}`

How can I achieve this in Typescript while preventing repeated letters, so "a" "b-d" "a-c-d" and "d-c-a" are ok but "a-a-c" is not allowed.

2 Answers 2

1
type Letter = 'a' | 'b' | 'c' | 'd' | 'e'

type Variation<T> =
    (T extends `${infer A}-${infer B}`
        ? (B extends `${infer BA}-${infer BB}`
            ? (
                `${A}-${Exclude<Letter, A>}-${Exclude<Exclude<Letter, BA>, A>}`
            )
            : (`${A}-${Exclude<Letter, A>}`)
        )
        : T
    );

const a: Variation<'a'> = 'a';
const b: Variation<'a-b'> = 'a-b';
const c: Variation<'a-b-c'> = 'a-b-c';

const d: Variation<'a-b-a'> = 'a-b-a'; // Error
const e: Variation<'a-d-d'> = 'a-d-d'; // Error
const f: Variation<'a-a-a'> = 'a-a-a'; // Error
Sign up to request clarification or add additional context in comments.

Comments

1

my solution is independent of combination length (:

type StringContainsString<A, B> = B extends string
  ? A extends `${B}${infer Rest}`
    ? true
    : A extends `${infer Rest}${B}`
    ? true
    : false
  : false;

type OmitDupes<T> = T extends `${infer A}-${infer Rest}`
  ? StringContainsString<Rest, A> extends true
    ? never
    : `${A}-${OmitDupes<Rest>}`
  : T extends `${infer A}`
  ? A
  : never;

type Letter = "a" | "b" | "c" | "d";

export type Combo = OmitDupes<
  Letter | `${Letter}-${Letter}` | `${Letter}-${Letter}-${Letter}`
>;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.