When working with Typescript, it's important to note that cat
cannot be guaranteed to be just 1, 2, 3, 4, or 5
as it could also be something else entirely different. In order to handle this uncertainty, you must explicitly specify to Typescript that you are confident it will be of type Cat
.
The main issue arises when trying to concatenate 'cat' + someVar
and assign it to type Cat
, which the compiler does not allow.
It is crucial to exercise caution when employing this method, as essentially overriding the compiler's error means you must guarantee beforehand that what you're dealing with will consistently 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',
}
// Using [Cat.cat1, Cat.cat2 ...] instead would be a safer approach.
// It's generally advised against using dynamic enum values like in this case.
for (const i of [1,2,3,4,5]) {
const category: Cat = (('cat' + i) as Cat);
}
// The compiler would also allow this, but only because you've ensured that the type will always be of type Cat.
for (const i of ['dog']) {
const category: Cat = (('cat' + i) as Cat);
}