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

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

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 Denunciar

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 Denunciar

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