Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

66
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!