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

252
Visualizações
How to convert typescript types of strings to array of strings?

I've this type:

type myCustomType = "aaa" | "bbb" | "ccc";

I need to convert it to an array like this:

["aaa", "bbb", "ccc"]

How can I do this in typescript?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can't do it with string literal but you can do it with an enum

enum MyEnum {
  "aaa",
  "bbb",
  "ccc",
}

Object.keys(MyEnum).forEach(key => {
  console.log(key);
})

Repro here : https://stackblitz.com/edit/typescript-uqvach

over 4 years ago · Santiago Trujillo Relatório

0

Types do not exist in emitted code - you can't go from a type to an array.

But you could go the other way around, in some situations. If the array is not dynamic (or its values can be completely determined by the type-checker at the time it's initialized), you can declare the array as const (so that the array's type is ["aaa", "bbb", "ccc"] rather than string[]), and then create a type from it by mapping its values from arr[number]:

const arr = ["aaa", "bbb", "ccc"] as const;
type myCustomType = typeof arr[number];

Here's an example on the playground.

over 4 years ago · Santiago Trujillo Relatório

0

For example:

  const themeMode = ['light', 'dark'] as const;
  type MainTheme = typeof themeMode[number];
  const values = [...themeMode];

  // iterate on themeMode as const assertion
  values.map((theme) => console.log(theme));
over 4 years ago · Santiago Trujillo 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