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

69
Visualizações
Typescript type annotations with varible

I have a variable and I want to set the variable as typescript type annotations.

type mytype = "image1" | "image2" | "image3"

images: mytype;

That is no problem, but I want to generate the mytype from an Array. How is that possible?

images = ["image1", "image2", "image3"]
mytype = images.map(i => '"' + i + '"').join(' | ')
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Do you think like this?

const images = ["image1", "image2", "image3"] as const;
type mytype = typeof images[number]; // mytype is now "image1" | "image2" | "image3"
about 4 years ago · Juan Pablo Isaza Relatório

0

I would use an enum for this case, unfortunately I don't think you can create the type on the fly based on dynamic values (or if you should, it defeats the purpose of ts).

https://www.typescriptlang.org/docs/handbook/enums.html

enum Images {
    ImageType1 = 'image1',
    ImageType2 = 'image2',
    ...
};
const values = Object.values(Images); // will be an array ['image1', 'image2', ...];

// use as a type
const foo = (image: Images) => {
   // do stuff, "image" will be restricted to 'image1' | 'image2' | ... values
}
about 4 years ago · Juan Pablo Isaza Relatório

0

There are two options to tell Typescript you want to assign an array to a variable:

1. Using the [] operator

The easiest and best way is to use [] after your type

type mytype = "image1" | "image2" | "image3"

images: mytype[];

2. Casting a type to an Array

type mytype = "image1" | "image2" | "image3"

images: Array<mytype>;
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