简体   繁体   English

无法将字符串枚举 typescript 定义为字符串不可分配

[英]Cannot define string enum typescript as string is not assignable

enum Cat {
    cat1 = 'cat1',
    cat2 = 'cat2',
    cat3 = 'cat3',
    cat4 = 'cat4',
    cat5 = 'cat5'
}
const category: Cat = 'cat' + cat

Why do I get a typescript error for that?为什么我会收到 typescript 错误? cat is a number, so category is a string. cat是一个数字,所以category是一个字符串。 But I want to define some specific string values for this variable.但我想为这个变量定义一些特定的字符串值。

Type 'string' is not assignable to type 'Cat'.

I assume you want category to be one of Cat, not the enum itself.我假设您希望类别成为 Cat 之一,而不是枚举本身。 so所以

const cat = 4;
const category = Cat[`cat${cat}`] // category: Cat.cat4

This also gives you type safety if trying to access a number out of range.如果尝试访问超出范围的数字,这也可以为您提供类型安全。 playground 操场

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'.

Typescript cant ensure that cat is 1,2,3,4, or 5 since it could also be someThingElse . Typescript 不能确保cat1,2,3,4, or 5因为它也可能是someThingElse Therefore you have to tell typescript that you are sure its gonna be of type Cat因此,您必须告诉 typescript 您确定它是Cat类型

The issue here is that the compiler wont allow 'cat' + someVar to be used as type Cat .这里的问题是编译器不允许将'cat' + someVar用作类型Cat

Please be cautious when using this, since you essentially overwrite the compilers error.使用它时请小心,因为您实际上会覆盖编译器错误。 You really need to make sure that whatever you're doing before will always be a valid 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);
}

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

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