stratis
stratis

Reputation: 8042

Nested tuple spread distributivity

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.

Upvotes: 2

Views: 98

Answers (2)

Thomas
Thomas

Reputation: 12637

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];

Upvotes: 1

Tobias S.
Tobias S.

Reputation: 23835

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.

Upvotes: 3

Related Questions