Home > Software engineering >  How to get the value of keys from an array of objects in Typescript?
How to get the value of keys from an array of objects in Typescript?

Time:12-01

I have the array:

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

And the 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>? In this case the typeStudy can be either "ENG" or "RU".

CodePudding user response:

If you could declare studyTypes as a const, it should be like this:

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.

Here's an example from my VSCode checking for lint errors: dynamic types

CodePudding user response:

You can define a new type as literal type.

type TypeStudy = "ENG" | "RU";

and then

React.useState<TypeStudy>

CodePudding user response:

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 could also use a map to extract the values from the objects and set that as the type.

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