【问题标题】:Extract a type from a const string array [duplicate]从 const 字符串数组中提取类型
【发布时间】:2020-07-11 16:25:39
【问题描述】:

我知道在 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() 之类的东西。此外,我也没有在键/值对象中为这些东西定义合理的值,因此使用对象作为起点感觉很愚蠢。

【问题讨论】:

  • ...你试过了吗?
  • 哈哈,是吗?它会给你一个带有“0”的类型| "1" | "2" | “长度” | “推”等...我需要值而不是键。
  • 如果你做 keyof typeof 它会的,是的。它们是数组类型的键。不过,您的问题只是显示了一个省略号;说明您尝试过的内容和发生的事情会很有帮助。
  • 谢谢,但省略号是为了表示我没有线索:)

标签: typescript


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2022-01-08
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多