为什么需要扩展{0:T}来强制TypeScript中泛型数组的长度?
我看到了这段代码,它展示了如何在TypeScript中强制执行泛型数组的长度。代码片段复制如下:为什么需要扩展{0:T}来强制TypeScript中泛型数组的长度?,typescript,Typescript,我看到了这段代码,它展示了如何在TypeScript中强制执行泛型数组的长度。代码片段复制如下: type MyArray<T, Length extends number> = Array<T> & { length: Length } type MyArray<T extends any, L extends number> = Array<T> & { 0: T; length: L; } const
type MyArray<T, Length extends number> = Array<T> & { length: Length }
type MyArray<T extends any, L extends number> = Array<T> & {
0: T;
length: L;
}
const foo1: MyArray<number, 5> = [1, 2, 3, 4, 5];
键入MyArray=Array&{length:length}
唯一的问题是,它不起作用。从中可以看出
它失败,出现以下错误:
Type 'string[]' is not assignable to type 'MyArray<string, 3>'.
Type 'string[]' is not assignable to type '{ length: 3; }'.
Types of property 'length' are incompatible.
Type 'number' is not assignable to type '3'.(2322)
类型“string[]”不能分配给类型“MyArray”。
类型“string[]”不能分配给类型“{length:3;}”。
属性“length”的类型不兼容。
类型“number”不可分配给类型“3”。(2322)
后来在twitter的帖子中,有人提出了一个有效的解决方案
现转载如下:
type MyArray<T, Length extends number> = Array<T> & { length: Length }
type MyArray<T extends any, L extends number> = Array<T> & {
0: T;
length: L;
}
const foo1: MyArray<number, 5> = [1, 2, 3, 4, 5];
键入MyArray=Array&{
0:T;
长度:L;
}
常量foo1:MyArray=[1,2,3,4,5];
从这一点可以看出
问题是,
{0:T}
有什么区别?为什么扩展它会使代码正常工作?我不确定,但我想知道这是否与稀疏数组的可能性有关?添加{0:T}需要设置第一个索引。