typescript 嵌套元组扩展分布

dxxyhpgq  于 2023-01-31  发布在  TypeScript
关注(0)|答案(2)|浏览(117)

今天我碰到了这个:

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

这是什么,有记录吗
如果我这样做,我得到预期的行为:

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

我不是在寻找一个解决方案,而是要了解发生了什么。

nbysray5

nbysray51#

它确实有文档记录。请参见Variadic tuple types PR
T的类型参数是联合类型时,该联合分布在元组类型上。例如,使用X | Y | Z作为T的类型参数示例化的[A, ...T, B]产生[A, ...T, B]的示例化的联合,其中XYZ分别作为T的类型参数。
第二个示例没有分发,因为spread元素的类型不是union,而是包含union作为第一个元素的元组。

vnjpjtjt

vnjpjtjt2#

想想这个:

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

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

我们的例子只是一个特例,两个元组都只有一个元素,其中[1,2]|[3,2]恰好等于[1|3, 2],但是即使两个元组的长度都是2,结果也可能非常不同:

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

相关问题