【问题标题】:How to get the value of keys from an array of objects in Typescript?如何从 Typescript 中的对象数组中获取键的值?
【发布时间】:2022-01-07 12:52:38
【问题描述】:

我有数组:

const studyTypes = [
   {
     value: "ENG",
     label: "ENG-RU",
   },
   {
     value: "RU",
     label: "RU-ENG",
   },
];

还有状态:

const [typeStudy, setTypeStudy] = React.useState<string>("ENG");

如何在打字稿中指定我的typeStudy 只能从studyTypes 数组中获取value 之一,而不是&lt;string&gt;?在这种情况下,typeStudy 可以是“ENG”或“RU”。

【问题讨论】:

标签: javascript reactjs typescript


【解决方案1】:

如果你可以将 studyTypes 声明为 const,它应该是这样的:

const studyTypes = [
   {
     value: "ENG",
     label: "ENG-RU",
   },
   {
     value: "RU",
     label: "RU-ENG",
   },
] as const; // as const is important for this step

type Value = typeof studyTypes[number]['value'];


const testValue: Value = "PQR" // This will throw a type error.

这仅适用于 Typescript v3.4 或更高版本。

这是我的 VSCode 检查 lint 错误的示例:

【讨论】:

  • 是的。有用。谢谢!
【解决方案2】:

您可以将新类型定义为文字类型。

type TypeStudy = "ENG" | "RU";

然后

React.useState<TypeStudy>

【讨论】:

    【解决方案3】:

    如果仅限于这两个选项,一个简单的方法是在类型中准确指定。

    const [typeStudy, setTypeStudy] = React.useState<'ENG'|'RU'>("ENG");
    

    您还可以使用映射从对象中提取值并将其设置为类型。

    type studyValues = typeof studyTypes.map(study => study.value)
    const [typeStudy, setTypeStudy] = React.useState<studyValues>
    

    【讨论】:

    • 但是如果数组中有很多对象怎么办?我在这里展示了两个数组以进行说明,实际上我还有更多。我无法全部列出。
    • 我是这么认为的。我已经更新了我的答案以反映这一点。
    • @Etin 在使用typeof 获取内部值时,您不能执行像map 这样的函数调用,因此此更新似乎也不起作用。我在答案中添加了正确的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    • 2021-12-06
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多