今天我碰到了这个:
type Test = [...[1]|[3], 2] // ^? type Test = [1, 2] | [3, 2]
这是什么,有记录吗如果我这样做,我得到预期的行为:
type Test = [...[1|3], 2] // ^? type Test = [1 | 3, 2]
我不是在寻找一个解决方案,而是要了解发生了什么。
nbysray51#
它确实有文档记录。请参见Variadic tuple types PR:当T的类型参数是联合类型时,该联合分布在元组类型上。例如,使用X | Y | Z作为T的类型参数示例化的[A, ...T, B]产生[A, ...T, B]的示例化的联合,其中X、Y和Z分别作为T的类型参数。第二个示例没有分发,因为spread元素的类型不是union,而是包含union作为第一个元素的元组。
T
X | Y | Z
[A, ...T, B]
X
Y
Z
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,结果也可能非常不同:
[1,2]|[3,2]
[1|3, 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];
2条答案
按热度按时间nbysray51#
它确实有文档记录。请参见Variadic tuple types PR:
当
T
的类型参数是联合类型时,该联合分布在元组类型上。例如,使用X | Y | Z
作为T的类型参数示例化的[A, ...T, B]
产生[A, ...T, B]
的示例化的联合,其中X
、Y
和Z
分别作为T
的类型参数。第二个示例没有分发,因为spread元素的类型不是union,而是包含union作为第一个元素的元组。
vnjpjtjt2#
想想这个:
我们的例子只是一个特例,两个元组都只有一个元素,其中
[1,2]|[3,2]
恰好等于[1|3, 2]
,但是即使两个元组的长度都是2,结果也可能非常不同: