Typescript cant ensure that cat is 1,2,3,4, or 5 since it could also be someThingElse. Therefore you have to tell typescript that you are sure its gonna be of type Cat
The issue here is that the compiler wont allow 'cat' + someVar to be used as type 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);
}