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 在这种情况下,为什么不从参数推断泛型值N?_Typescript_Generics - Fatal编程技术网

Typescript 在这种情况下,为什么不从参数推断泛型值N?

Typescript 在这种情况下,为什么不从参数推断泛型值N?,typescript,generics,Typescript,Generics,这个问题: 询问如何创建需要两个长度相同的数组的函数 这是我试图解决的问题 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<

这个问题:

询问如何创建需要两个长度相同的数组的函数

这是我试图解决的问题

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. 
type arrayOfficedLength=readonly T[]和{length:N};
常数a1:ArrayOfficedLength=[1]作为常数//预期误差
常数a2:ArrayOfficedLength=[1,2]作为常数;
函数myFunction(array1:ArrayOfficedLength

如前所述,如果您显式地声明了泛型值
N
——arrray的长度,则此代码仅给出TypeScript错误


为什么TypeScript无法从传递到函数中的参数推断出值N?

您需要提示编译器期望元组类型。否则编译器会将数组文本(如
[2,3,4]
扩展到
数字[]
。提示的形式通常是在类型注释或泛型约束中包含一个元组类型;最好是某个元组类型的并集,它不会妨碍您的操作:

function myFunction<N extends number>(
    array1: ArrayOfFixedLength<any, N> | [never],
    array2: ArrayOfFixedLength<any, N & {}> | [never]) {
    return true;
}
我觉得不错。好吧,希望有帮助,祝你好运


Ugh.我越来越意识到,虽然typescript可能可以做你想做的一切,但要做到这一点很难。
myFunction([1, 2, 3] as const, [2, 3, 4] as const); // okay
myFunction([1, 2] as const, [1, 2, 3] as const); // error
myFunction([1, 2, 3], [2, 3, 4]); // okay
myFunction([1, 2], [1, 2, 3]); // error