Home > OS >  Nested tuple spread distributivity
Nested tuple spread distributivity

Time:01-30

Today I bumped into this:

type Test = [...[1]|[3], 2]
//   ^? type Test = [1, 2] | [3, 2]

What is this? Is it documented anywhere?

If I do this instead I get the expected behaviour:

type Test = [...[1|3], 2]
//   ^? type Test = [1 | 3, 2] 

I'm not looking for a solution here but rather to understand what's going on.

CodePudding user response:

It is indeed documented. See the Variadic tuple types PR:

When the type argument for T is a union type, the union is spread over the tuple type. For example, [A, ...T, B] instantiated with X | Y | Z as the type argument for T yields a union of instantiations of [A, ...T, B] with X, Y and Z as the type argument for T respectively.

Your second example does not distribute because the type of the spread element is not a union, but rather a tuple containing a union as its first element.

CodePudding user response:

Consider this:

type Test = [...[]|[1][3,4,5], 2];

// which is equivalent to
type Test = [2] | [1,2] | [3,4,5,2];

Your example is just a special case where both of the tuples you spread have just a single item. Where [1,2]|[3,2] happen to be equivalent to [1|3, 2]. But even with two tuples of length 2 the results can be very different:

type Test = [...[1,2]|[3,4], 5];
// results in 
type Test = [1,2,5] | [3,4,5];

// and is not the same as
type NotTest = [1|3, 2|4, 5];
// because that means:
type NotTest = [1,2,5] | [1,4,5] | [1,3,5] | [1,4,5];
  • Related