[英]How to get the value of keys from an array of objects in Typescript?
I have the array:我有数组:
const studyTypes = [
{
value: "ENG",
label: "ENG-RU",
},
{
value: "RU",
label: "RU-ENG",
},
];
And the state:和 state:
const [typeStudy, setTypeStudy] = React.useState<string>("ENG");
How can I specify in typescript that my typeStudy
can only take one of the value
from the studyTypes
array instead of a <string>
?我如何在 typescript 中指定我的
typeStudy
只能从studyTypes
数组中获取value
之一而不是<string>
? In this case the typeStudy
can be either "ENG" or "RU".在这种情况下,
typeStudy
可以是“ENG”或“RU”。
If you could declare studyTypes as a const, it should be like this:如果你可以将 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.
This will only work with Typescript v3.4 or greater.这仅适用于 Typescript v3.4 或更高版本。
Here's an example from my VSCode checking for lint errors:这是我的 VSCode 检查 lint 错误的示例:
A simple way to do this, if it's limited to those two options is to specify exactly that in the type.如果仅限于这两个选项,那么一种简单的方法是在类型中准确指定。
const [typeStudy, setTypeStudy] = React.useState<'ENG'|'RU'>("ENG");
You can define a new type as literal type.您可以将新类型定义为文字类型。
type TypeStudy = "ENG" | "RU";
and then接着
React.useState<TypeStudy>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.