Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.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_Typescript Typings_Typescript Generics - Fatal编程技术网

在TypeScript中检测固定长度元组类型与数组类型

在TypeScript中检测固定长度元组类型与数组类型,typescript,typescript-typings,typescript-generics,Typescript,Typescript Typings,Typescript Generics,我有一个泛型函数,我想让它只接受固定长度(可能是混合类型)元组作为类型参数。我事先不知道可能的元组类型-它应该接受任何固定长度的元组 doSomething<[number, string, boolean]>(); // this should be okay doSomething<number[]>(); // this should throw a compiler error doSomething();//这应该没问题 doSomething();//这将引

我有一个泛型函数,我想让它只接受固定长度(可能是混合类型)元组作为类型参数。我事先不知道可能的元组类型-它应该接受任何固定长度的元组

doSomething<[number, string, boolean]>(); // this should be okay
doSomething<number[]>(); // this should throw a compiler error
doSomething();//这应该没问题
doSomething();//这将引发编译器错误
我知道我可以将长度限制为特定的数字文字(为简洁起见,省略了数组检查):

type LengthOf={
长度:N;
}

函数doSomething我不确定您为什么要这样做,但您可以加强,使其只接受
长度
属性小于
数字
的数组类型:

function doSomething<
    T extends (number extends T['length'] ? [] : any[])
>() { };
函数doSomething<
T扩展(数字扩展T['length']?[]:任意[])
>() { };
这将允许固定长度元组或长度为数字文本并集的元组,如

doSomething();//可以
doSomething();//可以
不允许使用数组或开放元组时(使用):

doSomething();//错误
doSomething();//错误

function doSomething<
    T extends (number extends T['length'] ? [] : any[])
>() { };
doSomething<[number, string, boolean]>(); // okay
doSomething<[number, string, boolean?]>(); // okay
doSomething<number[]>(); // error
doSomething<[number, string, ...boolean[]]>(); // error