Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an exhaustive switch statement with ambient enum types

Tags:

typescript

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?

like image 795
dewakaputo Avatar asked Oct 26 '25 21:10

dewakaputo


1 Answers

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

like image 178
jcalz Avatar answered Oct 29 '25 17:10

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!