Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

333
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda