Home > front end >  Typescript type annotations with varible
Typescript type annotations with varible

Time:11-09

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(' | ')

CodePudding user response:

Do you think like this?

const images = ["image1", "image2", "image3"] as const;
type mytype = typeof images[number]; // mytype is now "image1" | "image2" | "image3"

CodePudding user response:

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

CodePudding user response:

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
}
  • Related