【发布时间】:2019-12-06 12:40:21
【问题描述】:
假设我想对给定数组强制执行严格类型,这样:
- 它可以包含任意数量(也就是零或更多)
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.
【问题讨论】:
-
使用自定义类型保护是否可行? typescriptlang.org/play/#code/…
标签: javascript arrays typescript