typescript - 从 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() 之类的东西。此外,我也没有在键/值对象中为这些东西定义合理的值,因此使用对象作为起点感觉很愚蠢。
解决方案
您可以访问[number]
数组typeof someOptions
以获取联合类型的值:
const someOptions = ["a", "b", "c"] as const;
type SomeType = typeof someOptions[number]
// SomeType is:
// "a" | "b" | "c"
推荐阅读
- java - 我可以用 Java 代码分析 .hprof 文件吗?
- python-3.x - Matplotlib 在没有 rc_context、ax.yaxis 等的情况下操作文本字体属性
- dart - DropdownButton 无法更新它的值(null)
- spring - MockMvc 在响应后不返回创建的资源
- angular - 当 AOT 编译器打开而不是 JIT 时,会自动添加 Flex 布局样式
- sparql - 简单的 SPARQL 查询不给出海龟文件的结果
- excel - 我需要跳过我的 vba 按钮中的空单元格并在不为空时打开
- typescript - Typescript 类中的 Node-ipc
- docker - 加快 Confluent docker 加载时间
- swift - 从可选的通用扩展返回 nil