我有一个泛型函数,我想让它只接受固定长度(可能是混合类型)元组作为类型参数。我不知道可能的元组类型在预先-它应该接受任何固定长度元组。
doSomething<[number, string, boolean]>(); // this should be okay
doSomething<number[]>(); // this should throw a compiler error我知道我可以将长度限制在一个特定的数字文本(为简洁而省略的数组检查):
type LengthOf<N extends number> = {
length: N;
}
function doSomething<T extends LengthOf<2>(){};
doSomething<[any, any]>(); // ok
doSomething<[any]>(); // error但我不能使用这种方法将长度限制为任何数字文字,因为任何数字文字都会扩展数字,这也是可变长度数组的length类型。
这在TypeScript中是可能的吗?
发布于 2021-02-17 03:41:34
我不知道您为什么要这样做,但是您可以增强属约束,以便它只接受length属性比number更窄的数组类型
function doSomething<
T extends (number extends T['length'] ? [] : any[])
>() { };这将允许固定长度的元组或长度为数值文本(如带有可选元素的元组 )的合并的元组,
doSomething<[number, string, boolean]>(); // okay
doSomething<[number, string, boolean?]>(); // okay当不允许数组或开放元组(使用rest元素)时:
doSomething<number[]>(); // error
doSomething<[number, string, ...boolean[]]>(); // errorhttps://stackoverflow.com/questions/66235379
复制相似问题