enum Cat {
cat1 = 'cat1',
cat2 = 'cat2',
cat3 = 'cat3',
cat4 = 'cat4',
cat5 = 'cat5'
}
const category: Cat = 'cat' cat
為什么我會收到打字稿錯誤?cat是數字,category字串也是。但我想為這個變數定義一些特定的字串值。
Type 'string' is not assignable to type 'Cat'.
uj5u.com熱心網友回復:
我假設您希望 category 成為 Cat 之一,而不是列舉本身。所以
const cat = 4;
const category = Cat[`cat${cat}`] // category: Cat.cat4
如果嘗試訪問超出范圍的數字,這也可以為您提供型別安全。操場
enum Cat {
cat1 = 'cat1',
cat2 = 'cat2',
cat3 = 'cat3',
cat4 = 'cat4',
cat5 = 'cat5'
}
const cat = 4;
const category = Cat[`cat${cat}`]
const cat6 = 6;
const category6 = Cat[`cat${cat6}`] // Property 'cat6' does not exist on type 'typeof Cat'.
uj5u.com熱心網友回復:
打字稿不能確保cat是1,2,3,4, or 5因為它也可能是someThingElse. 因此你必須告訴打字稿你確定它會是型別Cat
這里的問題是編譯器不允許'cat' someVar用作 type Cat。
使用它時請小心,因為您實際上會覆寫編譯器錯誤。你真的需要確保你之前做的任何事情都將永遠是一只有效的貓。
enum Cat {
cat1 = 'cat1',
cat2 = 'cat2',
cat3 = 'cat3',
cat4 = 'cat4',
cat5 = 'cat5',
}
const category: Cat = (('cat' cat) as Cat);
enum Cat {
cat1 = 'cat1',
cat2 = 'cat2',
cat3 = 'cat3',
cat4 = 'cat4',
cat5 = 'cat5',
}
// this would be of however [Cat.cat1, Cat.cat2 ...] would be a lot safer.
// I would generally suggest not tot use dynamic enum values like this.
for (const i of [1,2,3,4,5]) {
const category: Cat = (('cat' i) as Cat);
}
// the compiler would allow this as well, since you ensure that you know the type is going to be if type Cat
for (const i of ['dog']) {
const category: Cat = (('cat' i) as Cat);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390800.html
標籤:javascript 打字稿
下一篇:TypeScript陣列差異
