I have the following function:
function mapPlaceToEmoji(place: Place): string {
switch (place) {
case Place.FIRST:
return '🥇';
case Place.SECOND:
return '🥈';
case Place.THIRD:
return '🥉';
}
}
It works perfectly fine if I use a non-ambient enum:
enum Place {
FIRST,
SECOND,
THIRD,
}
However, it doesn't work with an ambient enum:
declare enum Place {
FIRST,
SECOND,
THIRD,
}
I get the following error:
Function lacks ending return statement and return type does not include 'undefined'.(2366)
How can I do an exhaustive switch statement with ambient enum types?
It's a known bug in TypeScript; see microsoft/TypeScript#16977. Until and unless this gets fixed, you can work around it by explicitly setting the values like this:
declare enum Place {
FIRST = 0,
SECOND = 1,
THIRD = 2,
}
Playground link to code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With