gotchatypescriptMajor
Difference between string enums and string literal types in TS
Viewed 0 times
literalandenumsbetweendifferencestringtypes
Problem
Assuming I want to ensure that
I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check).
The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases.
myKey in { myKey: '' } only contains the strings foo, bar, baz, I could achieve this in two ways.// with a String Literal Type
type MyKeyType = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check).
The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases.
Solution
The key thing to understand is that the values of string enums are opaque.
The intended use case for a string enum is that you don't want other code to know or care what the literal string backing
The intended use case for a string enum is that you don't want other code to know or care what the literal string backing
MyKeyType.FOO is. This means that you won't be able to, say, pass the literal string "bar" to a function accepting a MyKeyType -- you'll have to write MyKeyType.BAR instead.Context
Stack Overflow Q#49761972, score: 78
Revisions (0)
No revisions yet.