I found this type Tuple<string, 10>
in Mantine documentation but I couldn't grasp the concept of it. I tested in TypeScript playground and it throws compile error.
我在Mantine文档中发现了这种类型的Tuple
,但我无法理解它的概念。我在TypeScript操场上进行了测试,它引发了编译错误。
// Object of arrays with 10 colors
colors: Record<string, Tuple<string, 10>>;
When I look up TypeScript documentation there is no explanation about the first type in chevron is item type in array and the second number represents number of items in array. Can anyone share me some insight how this type definition works?
当我查找TypeScript文档时,并没有解释V形中的第一个类型是数组中的项类型,第二个数字表示数组中的项数。有人能和我分享一下这种类型定义是如何工作的吗?
更多回答
优秀答案推荐
I took a look at it in the Github repository of Mantine. Tuple
is a custom type that is defined like this:
我在Mantine的Github存储库中看了一眼。Tuple是一种自定义类型,其定义如下:
type _TupleOf<
T,
N extends number,
R extends unknown[]
> = R["length"] extends N ? R : _TupleOf<T, N, [T, ...R]>;
export type Tuple<T, N extends number> = N extends N
? number extends N
? T[]
: _TupleOf<T, N, []>
: never;
As you can see, we're dealing with recursive types here. Essentially, Tuple
produces an fixed-length array like structure structure. Record<string, Tuple<string, 10>>
will be inferred to:
正如您所看到的,我们在这里处理递归类型。从本质上讲,Tuple产生了一种固定长度的类似阵列的结构。记录<string,元组<string,10>>将被推断为:
{
[x: string]: [string, string, string, string, string, string, string, string, string, string];
}
更多回答
Oh, I had no idea it was a custom type. Thanks a lot for the explanation!
哦,我不知道这是一个自定义类型。非常感谢你的解释!
我是一名优秀的程序员,十分优秀!