V
V
Vlad2021-08-03 01:40:24
typescript
Vlad, 2021-08-03 01:40:24

What is the correct way to "combine type"?

There is this type: How can I make him AND
type char = "A" | "B" | "C" | "D";

type t1 = ["A", "B", "C", "D"];
type t2 = "ABCD";

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-08-03
@TRen208

Since the order in a union is not defined, you can only get a union of all possible options:

type Char = "A" | "B" | "C" | "D";
type ConcatMap<T> = T extends unknown
    ? {} extends T[keyof T]
        ? `${string & keyof T}`
        : `${string & keyof T}${ConcatMap<T[keyof T]>}`
    : never;
type MapChars<C extends Char> = {
    [K in C]: MapChars<Exclude<C, K>>
};
type Split<S extends string> = S extends `${infer H}${infer Tail}`
    ? [H, ...Split<Tail>]
    : [];
type T1 = Split<T2>;
type T2 = ConcatMap<MapChars<Char>>;

https://www.typescriptlang.org/play?#code/C4TwDgpg...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question