DEV Community

Discussion on: Enum in typescript

Collapse
 
moseskarunia profile image
Moses Karunia

What happens if we omit <any>? Isn't it should infer any by default?

I personally, prefers to write it in 1. Splitting into 1 enum and 1 class seems weird.

One of the problem is when we try to deserialize string to enum.

E.g. when getting string from rest call. When this happens, I think we should make our parameter as Terrain | string anyway right?

Collapse
 
kryz profile image
Kryz • Edited

If you remove any you will get an error. Actually any should be avoided.

Alternative solution is:

class Terrain {
    public static isValid(value: string): boolean {
        return Object.keys(TerrainType).includes(value);
    }
}

But it works in >= ES7. Keep in mind that key and value in this enum must be the same, for example OCEAN = "OCEAN"

I find enum/class much cleaner that creating many static const in the class. Why do you find it weird?
It's completely fine to extract possible values to an enum/object/array/dictionary:

First if I had to add a new option adding it to an enum would be much cleaner than modifying the class and having for example 10 static constants in the class + modifying IF condition.

Secondly maybe other parts of your application will use this enum if your project starts to grow. In this case I would even consider to put this enum into a separate file. All parts would import the enum and would not depend on the Terrain class.

when getting string from rest call...
I think you always get a string (or number or null) from the rest call.
You can create an enum var like that:

const valueFromRest: string = "OCEAN";
const value: TerrainType = (<any>TerrainType)[valueFromRest];