typescript 将字符串数组转为联合类型

ts中,如何将字符串数组转为联合类型,比如:

const arr = ['name', 'age', 'location', 'email'];

// 通过类型操作之后得到下面这种类型
type arrType = 'name' | 'age' | 'location' | 'email'

说明: 将字符串数组中的每一个字符串都作为联合类型中的一个类型

阅读 16.4k
2 个回答
const arr = ['name', 'age', 'location', 'email'] as const;
type A = typeof arr[number];
type arr = ('name'| 'age'| 'location'| 'email')[];

type UnionType<T> = T extends (infer P)[] ? P : never;

type arrType = UnionType<arr>;

这样?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题