首页 > 解决方案 > 带有索引类型签名的 typeof 元组代表什么?

问题描述

我遵循 Typescript 代码,但我无法真正理解最后一行代码

const tuple = <T extends string[]>(...args: T) => args;
const ButtonTypes = tuple('default', 'primary', 'ghost', 'dashed', 'danger', 'link');
export type ButtonType = (typeof ButtonTypes)[number];

这是我所说的更明确的路线。

(typeof ButtonTypes)[number]

更新

这直接来自Ways to get string literal type of array values without enum 开销

标签: typescript

解决方案


tuple是一个接受参数的函数,并返回一个包含所有参数的数组。例如,tuple('foo', 'bar')将评估为['foo', 'bar']

const ButtonTypes = tuple('default', 'primary', 'ghost', 'dashed', 'danger', 'link');

你会得到一个包含所有这些字符串的数组:

const ButtonTypes = ['default', 'primary', 'ghost', 'dashed', 'danger', 'link'];

然后,使用(typeof foo)[number],您将检索foo可以通过数字索引访问的变量的所有属性。因此,就像执行以下操作一样:

export type ButtonType = "default" | "primary" | "ghost" | "dashed" | "danger" | "link";

只有较少重复。


推荐阅读