假设我有一个看起来像这样的工会
type Colors = 'red' | 'blue' | 'pink'
是否可以针对此联合对数组进行类型检查并确保该数组包含所有类型?
IE。:
const colors: UnionToTuple<Colors> = ['red', 'blue'] // type error, missing 'pink'
const colors: UnionToTuple<Colors> = ['red', 'blue', 'pink'] // no error
最佳答案
从 this 获取想法答案,您可以使用传递的数组 T 的类型参数来创建一个类型检查的函数。将其键入为 T extends Colors[]
确保数组的每一项都在 Colors
中, 并将其键入为 [Colors] extends [T[number]] ? unknown : 'Invalid'
确保 Colors 类型的每个项目都在传递的数组中:
type Colors = 'red' | 'blue' | 'pink';
const arrayOfAllColors = <T extends Colors[]>(
array: T & ([Colors] extends [T[number]] ? unknown : 'Invalid')
) => array;
const missingColors = arrayOfAllColors(['red', 'blue']); // error
const goodColors = arrayOfAllColors(['red', 'blue', 'pink']); // compiles
const extraColors = arrayOfAllColors(['red', 'blue', 'pink', 'bad']); // error
更一般地,将其包装在另一个函数中,以便您可以传递和使用联合类型的类型参数:
type Colors = 'red' | 'blue' | 'pink';
const arrayOfAll = <T>() => <U extends T[]>(
array: U & ([T] extends [U[number]] ? unknown : 'Invalid')
) => array;
const arrayOfAllColors = arrayOfAll<Colors>();
const missingColors = arrayOfAllColors(['red', 'blue']); // error
const goodColors = arrayOfAllColors(['red', 'blue', 'pink']); // compiles
const extraColors = arrayOfAllColors(['red', 'blue', 'pink', 'bad']); // error
关于javascript - 确保数组具有联合中的所有类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131681/