如何在TypeScript中创建只接受具有两个或更多元素的数组的类型?
needsTwoOrMore(["onlyOne"]) // should have error
needsTwoOrMore(["one", "two"]) // should be allowed
needsTwoOrMore(["one", "two", "three"]) // should also be allowed
Run Code Online (Sandbox Code Playgroud)
Ste*_*ams 21
这是一个老问题,答案很好(它对我也有帮助),但我在玩游戏时也偶然发现了这个解决方案。
我已经定义了一个类型化的元组 ( type Tuple<T> = [T, T];
),然后在它下面,我定义了两个或更多的数组,如上所述 ( type ArrayOfTwoOrMore<T> = { 0: T, 1: T } & T[];
)。
我突然想到尝试使用Tuple<T>
结构代替{ 0: T, 1: T }
,如下所示:
type ArrayOfTwoOrMore<T> = [T, T, ...T[]];
它奏效了。好的!它更简洁一些,并且在某些用例中可能更清晰。
值得注意的是,一组不会有是两个同类型的项目。类似的东西['hello', 2]
是一个有效的元组。在我的小代码片段中,它恰好是一个合适的名称,并且需要包含两个相同类型的元素。
KPD*_*KPD 19
这可以通过以下类型实现:
type ArrayTwoOrMore<T> = {
0: T
1: T
} & Array<T>
declare function needsTwoOrMore(arg: ArrayTwoOrMore<string>): void
needsTwoOrMore(["onlyOne"]) // has error
needsTwoOrMore(["one", "two"]) // allowed
needsTwoOrMore(["one", "two", "three"]) // also allowed
Run Code Online (Sandbox Code Playgroud)
Ole*_*nyi 11
2021 年更新:更短的符号:
type arrMin1Str = [string, ...string[]]; // The minimum is 1 string.
或者
type arrMin2Strs = [string, string, ...string[]]; // The minimum is 2 strings.
或者
type arrMin3Strs = [string, string, string, ...string[]]; // The minimum is 3 strings.
或者……等等
这只是@KPD 和@Steve Adams 答案的补充,因为所有指定的类型都相同。这应该是自 TypeScript 3.0+ (2018) 以来的有效语法。
type FixedTwoArray<T> = [T,T]
interface TwoOrMoreArray<T> extends Array<T> {
0: T
1: T
}
let x: FixedTwoArray<number> = [1,2];
let y: TwoOrMoreArray<string> = ['a','b','c'];
Run Code Online (Sandbox Code Playgroud)
扩展 Oleg 的答案,您还可以为任意最小长度的数组创建一个类型:
type BuildArrayMinLength<
T,
N extends number,
Current extends T[]
> = Current['length'] extends N
? [...Current, ...T[]]
: BuildArrayMinLength<T, N, [...Current, T]>;
type ArrayMinLength<T, N extends number> = BuildArrayMinLength<T, N, []>;
const bad: ArrayMinLength<number, 2> = [1]; // Type '[number]' is not assignable to type '[number, number, ...number[]]'.
const good: ArrayMinLength<number, 2> = [1, 2];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1943 次 |
最近记录: |