假设我想对给定的数组强制执行严格类型化,这样:
- 它可以包含任意数量的(也就是零个或多个)
number
- 必须包含一个或多个
string
...并且数组中number
和string
的顺序无关紧要,因此以下数组是有效的:
['foo', 1, 2, 3]
[1, 2, 'foo', 3]
['foo']
但是下面的数组是无效的:
[1, 2, 3]
(因为数组中至少需要一个string
)
几乎 对我有用的最接近的解决方案是将类型定义为:
/**
* Array must contain:
* - One or more string
* - Zero or more numbers
* @type
*/
type CustomArray = [string] & Array<number | string>
const a: CustomArray = ['foo', 1, 2, 3]; // Should pass (works as expected)
const b: CustomArray = [1, 2, 'foo', 3]; // Should pass (but doesn't with my code)
const c: CustomArray = ['string']; // Should pass (works as expected)
const d: CustomArray = [1, 2, 3]; // Should fail (works as expected)
但这意味着数组的第一个 元素必须是字符串,而不是强制整个数组的最小计数为 1。 You can test it out on TypeScript Playround here .
最佳答案
无法告诉 TypeScript 数组应该包含至少一个特定类型的元素。
你能做的最好的就是创建一个数字/字符串数组:
type CustomArray = (number | string)[];
或者
type CustomArray = Array<number | string>;
然后添加 required checks您向数组添加数据或从数组读取数据的位置。
关于javascript - 混合类型的数组,但在数组中具有特定类型的最小计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57249336/