【发布时间】:2020-06-12 20:01:10
【问题描述】:
这个问题:
TypeScript: Require that two arrays be the same length?
询问如何创建一个需要两个长度相同的数组的函数。
这是我的解决方案尝试。
type ArrayOfFixedLength<T extends any, N extends number> = readonly T[] & { length: N };
const a1: ArrayOfFixedLength<number, 2> = [1] as const; //expected error
const a2: ArrayOfFixedLength<number, 2> = [1, 2] as const;
function myFunction<N extends number>(array1: ArrayOfFixedLength<any, N >, array2: ArrayOfFixedLength<any, N>) {
return true;
}
myFunction<3>([1, 2, 3] as const, [2, 3, 4] as const);
myFunction<2>([1, 2] as const, [1, 2, 3] as const); //expected error
// However, if you don't specify the array length,
// It fails to error
myFunction([1, 2, 3] as const, [2, 3, 4] as const);
myFunction([1, 2] as const, [1, 2, 3] as const); // error is expected, but there is none.
如前所述,如果您明确声明通用值 N - 数组的长度,此代码只会给出 TypeScript 错误。
为什么 TypeScript 无法从传递给函数的参数中推断出值 N?
【问题讨论】:
标签: typescript generics