Is there any benefit of using enum?

#1

I’ve a type that has a string field which is supposed to take some known values (e.g. v1, v2, …, vn).
Is it better to make it an enum or it’s OK to just have it a string? e.g. will I get bette perf if I use enum?

0 Likes

#2

I don’t think there are performance benefits, but one big benefit is having a clearly defined data model or function interface. For example, if you have a type:

entity type TestResult {
    status: string enum('FAILED', 'PASSED', 'SKIPPED')
}

This is the correct usage:

TestResult.create({status: 'FAILED'});

This will throw an exception:

TestResult.create({status: 'UNKNOWN'})

In the case of functions you get automatic input validation and easy access in JavaScript:

type Logger {
    logMessage: function(level: string enum LogLevel, message: string) js server
}

enum type LogLevel {
    DEBUG
    INFO
    WARN
    ERROR
}

This is the correct usage:

Logger.logMessage('DEBUG', 'This is the correct usage');
Logger.logMessage(LogLevel.DEBUG, 'This is the correct usage');

This will throw an exception:

Logger.logMessage('TRACE', 'This will throw an exception');

And you won’t have to manually validate the input in your implementation.

1 Like