Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

339
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda