Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
最小长度的TypeScript数组_Typescript - Fatal编程技术网

最小长度的TypeScript数组

最小长度的TypeScript数组,typescript,Typescript,如何在TypeScript中创建一个只接受包含两个或更多元素的数组的类型 needsTwoOrMore(["onlyOne"]) // should have error needsTwoOrMore(["one", "two"]) // should be allowed needsTwoOrMore(["one", "two", "three"]) // should also be allowed 这可以通过以下类型完成: type ArrayTwoOrMore<T> = {

如何在TypeScript中创建一个只接受包含两个或更多元素的数组的类型

needsTwoOrMore(["onlyOne"]) // should have error
needsTwoOrMore(["one", "two"]) // should be allowed
needsTwoOrMore(["one", "two", "three"]) // should also be allowed

这可以通过以下类型完成:

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
类型ArrayTwoOrMore={
0:T
1:T
}&数组
声明函数needsTwoOrMore(arg:ArrayTwoOrMore):void
needsTwoOrMore([“onlyOne”])//有错误
needsTwoOrMore([“一”,“二])//允许
needsTwoOrMore([“一”,“二”,“三])//也允许
键入FixedTwoArray=[T,T]
接口TwoOrMoreArray扩展了数组{
0:T
1:T
}
设x:FixedTwoArray=[1,2];
设y:TwoOrMoreArray=['a','b','c'];

这是一个老问题,答案很好(它也帮助了我),但我只是在玩的时候偶然发现了这个解决方案

我已经定义了一个类型化的元组(
typetuple=[T,T];
),然后在下面,我定义了两个或更多的数组,如上所述(
typearrayoftwoormore={0:T,1:T}&T[];

我突然想到尝试使用
Tuple
结构来代替
{0:T,1:T}
,如下所示:

类型ArrayOfTwoOrMore=[T,T,…T[]

它成功了。美好的它更加简洁,在某些用例中可能更清晰


值得注意的是,元组不必是同一类型的两个项。类似于
['hello',2]
的内容是一个有效的元组。在我的小代码片段中,它恰好是一个合适的名称,需要包含两个相同类型的元素。

更新2021较短的符号:

键入arrMin1Str=[string,…string[]];//最小值为1个字符串。

键入arrMin2Strs=[string,string,…string[]];//最小值为2个字符串。

键入arrMin3Strs=[string,string,string,…string[]];//最小值为3个字符串。

或者……等等

这只是@KPD和@Steve Adams答案的一个补充,因为所有指定的类型都是相同的。
这应该是自TypeScript 3.0+(2018)以来的有效语法。

扩展Oleg的答案,您还可以为任意最小长度的数组创建类型:

键入BuildArrayMinLength<
T
N扩展数字,
电流扩展T[]
>=当前['length']扩展N
? […当前,…T[]
:BuildArrayMinLength;
输入ArrayMinLength=BuildArrayMinLength;
常量错误:ArrayMinLength=[1];//类型“[number]”不能分配给类型“[number,number,…number[]”。
const good:ArrayMinLength=[1,2];

基于。

如何使用界面实现这一点?说
items:Item[]=[],我需要至少1个
项目
@ColdCerberus没有区别。
Item[]
语法只是
Array
的糖。因此,就像答案中的示例had
ArrayTwoOrMore
一样,您可以拥有
ArrayTwoOrMore
。要将其更改为
ArrayOnOrmore
,只需复制
类型ArrayWoormore
定义并删除
1:T
行。虽然这种方法适用于数组声明,但在使用
array#map
将非空数组转换为其他数组时,TypeScript无法理解输出有一个
0
键:
属性“0”在类型“MyType[]”中丢失,但在类型“{0:MyType;}”中是必需的。
不是最漂亮的,但工作起来很有魅力!