javascript - 确保数组具有联合中的所有类型

标签 javascript typescript

假设我有一个看起来像这样的工会

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/

相关文章:

javascript - 仅当旁边有空格时,如何加宽 div?

javascript - jquery代码问题,有合适的格式吗?

javascript - 我可以更改另一个变量中的 javascript 变量吗?

node.js - 为什么在 Node.js 代码中使用 import 和 require()?

javascript - 使用扩展运算符从 ES6 中的对象中删除目标参数

javascript - FileList 和 File[](又名文件数组)之间有什么区别

typescript - 为什么未收到我的 x-functions-key Azure Function header ?

JavaScript 碰撞函数

javascript - 在应用程序变量更改时回发 UpdatePanel

typescript - Firebase HTTPS 函数 - 在完成后台工作之前响应 200 状态代码