There exists a distinguishing factor between string enums and literal types in the transpiled code.
Let's compare the Typescript Code
// with a String Literal Type
type MyKeyType1 = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType2 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
Now let's observe the transpiled JavaScript Code
// or with a String Enum
var MyKeyType2;
(function (MyKeyType2) {
MyKeyType2["FOO"] = "foo";
MyKeyType2["BAR"] = "bar";
MyKeyType2["BAZ"] = "baz";
})(MyKeyType2 || (MyKeyType2 = {}));
It can be seen that no generated code is produced for the string literal. This is because Typescripts Transpiler is solely utilized for ensuring type safety during transpilation. At runtime, string literals are converted to regular strings with no connection between the definition of the literal and its usage.
Hence, there is an additional option known as const enum
Consider this example
// with a String Literal Type
type MyKeyType1 = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType2 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
// or with a Const String Enum
const enum MyKeyType3 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
var a : MyKeyType1 = "bar"
var b: MyKeyType2 = MyKeyType2.BAR
var c: MyKeyType3 = MyKeyType3.BAR
This will be transpiled as follows
// or with a String Enum
var MyKeyType2;
(function (MyKeyType2) {
MyKeyType2["FOO"] = "foo";
MyKeyType2["BAR"] = "bar";
MyKeyType2["BAZ"] = "baz";
})(MyKeyType2 || (MyKeyType2 = {}));
var a = "bar";
var b = MyKeyType2.BAR;
var c = "bar" /* BAR */;
If you want to experiment further, you can access this link
I personally opt for the const enum scenario due to the ease of typing Enum.Values. Typescript efficiently handles the conversion process to achieve optimal performance during transpilation.