简体   繁体   English

带有变量的打字稿类型注释

[英]Typescript type annotations with varible

I have a variable and I want to set the variable as typescript type annotations.我有一个变量,我想将该变量设置为 typescript 类型注释。

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

images: mytype;

That is no problem, but I want to generate the mytype from an Array.那没问题,但我想从数组生成 mytype。 How is that possible?这怎么可能?

images = ["image1", "image2", "image3"]
mytype = images.map(i => '"' + i + '"').join(' | ')

Do you think like this?你是这样想的吗?

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

There are two options to tell Typescript you want to assign an array to a variable:有两个选项可以告诉 Typescript 您要将数组分配给变量:

1. Using the [] operator 1. 使用 [] 操作符

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 2. 将类型转换为数组

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

images: Array<mytype>;

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).我会在这种情况下使用枚举,不幸的是,我认为您无法根据动态值动态创建类型(或者,如果您应该这样做,它会违背 ts 的目的)。

https://www.typescriptlang.org/docs/handbook/enums.html 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM