1

Let's say that I have following type:

type ArrayType = ["AB"] | ["AB", "CD"] | ["X", "Y", "Z"];

I would like to transform it to the following type:

type TransformedArrayType = "AB" | "ABCD" | "XYZ";

How can I accomplish that in the Typescript?

1 Answer 1

2

You can join strings recursively using template literal types:

type ArrayType = ["AB"] | ["AB", "CD"] | ["X", "Y", "Z"];

type JoinTuple<T> = T extends [infer Head, ...infer Rest]
  ? `${Head & string}${JoinTuple<Rest>}` : ''

type Test = JoinTuple<["AB", "CD"]> // "ABCD"

type TransformedArrayType = JoinTuple<ArrayType> // "AB" | "ABCD" | "XYZ"

Playground

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way in TS to recursively iterate heterogeneous unions without chained conditionals?
@jsejcksn could you provide specific example of what you're trying to do?
I don't have a case: it was just something I wondered in the moment. I think the answer is "no" because the serial conditionals are needed to discriminate and get to leaves.

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.