typescript - 带有索引类型签名的 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 开销
解决方案
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";
只有较少重复。
推荐阅读
- postgresql - 在某些数据库上连接到 Postgres 花费的时间太长
- javascript - 视频 js 中跳跃的搜索栏
- karate - 在另一个变量中使用一个字符串变量的值是将所有特殊字符转换为十六进制代码
- sql - SQL Server 选择最近的记录(稍加改动)
- c++ - 在没有复制构造函数的对象的成员函数中启动 std::thread
- react-native - 如何在没有堆栈的情况下浏览 React Native 应用程序
- bash - Curl - 无效参数 null
- javascript - 显示 API 响应 - React JS
- laravel - Laravel 使用条件对用户进行身份验证
- c# - 如果 c# sqlClient 中有空表单,请不要保存信息