具有索引类型的typeof元组

如下所示

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

你知道ButtonType的最终类型是什么吗?

正确类型为

type ButtonType = "default" | "primary" | "ghost" | "dashed" | "link" | "text";

为什么会是这个结果?首先可以推断出ButtonTypes的类型是["default", "primary", "ghost", "dashed", "link", "text"]。然后,使用["default", "primary", "ghost", "dashed", "link", "text"][number]将会检索这个类型数组中的所有属性,使用数字索引对其访问,因此会出现上述所示的类型结果。

参考自:https://stackoverflow.com/questions/56897267/what-does-typeof-tuple-with-index-type-signature-represents?noredirect=1&lq=1

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注