Typescript – Difference between string enums and string literal types in TS

typescript

Assuming I want to ensure that 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.

Best Answer

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 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.

Related Topic