首页 > 解决方案 > 从 const 字符串数组中提取类型

问题描述

我知道在 Typescript 中你可以这样做:

const someOptions = {
  a: "",
  b: "",
  c: ""
} as const 


type SomeType = keyof typeof someOptions

我想做一些非常相似的事情,但然后使用数组作为输入。

const someOptions = ["a", "b", "c"] as const;
type SomeType = ...

这可能吗?

数组很方便,因为我可以将它直接传递给 Joi.string().valid() 之类的东西。此外,我也没有在键/值对象中为这些东西定义合理的值,因此使用对象作为起点感觉很愚蠢。

标签: typescript

解决方案


您可以访问[number]数组typeof someOptions以获取联合类型的值:

const someOptions = ["a", "b", "c"] as const;
type SomeType = typeof someOptions[number]
// SomeType is:
// "a" | "b" | "c"

推荐阅读