我有一個變數,我想將該變數設定為 typescript 型別注釋。
type mytype = "image1" | "image2" | "image3"
images: mytype;
那沒問題,但我想從陣列生成 mytype。這怎么可能?
images = ["image1", "image2", "image3"]
mytype = images.map(i => '"' i '"').join(' | ')
uj5u.com熱心網友回復:
你是這樣想的嗎?
const images = ["image1", "image2", "image3"] as const;
type mytype = typeof images[number]; // mytype is now "image1" | "image2" | "image3"
uj5u.com熱心網友回復:
有兩個選項可以告訴 Typescript 您要將陣列分配給變數:
1. 使用 [] 運算子
最簡單和最好的方法是[]在你的型別之后使用
type mytype = "image1" | "image2" | "image3"
images: mytype[];
2. 將型別轉換為陣列
type mytype = "image1" | "image2" | "image3"
images: Array<mytype>;
uj5u.com熱心網友回復:
我會在這種情況下使用列舉,不幸的是,我認為您無法根據動態值動態創建型別(或者,如果您應該這樣做,它會違背 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352807.html
標籤:javascript 细绳 打字稿
