Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

331
Views
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:

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".

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

You can define a new type as literal type.

type TypeStudy = "ENG" | "RU";

and then

React.useState<TypeStudy>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!