Search code examples
typescriptenums

Why does a specific string not conform to enum including that string?


If I have enum:

enum MyEnum {
  foo = 'FOO',
  bar = 'BAR',
}

the result of testing for confirmance of a const string behaves like:

type StringIsInEnum = 'FOO' extends MyEnum ? true : false; // false

Can someone explain why in this case, 'FOO' does not extend MyEnum?

MyEnum.foo will never change during runtime, and 'FOO' is a constant value, and so will also never change.


Solution

  • While TypeScript is generally a structural language enums are a bit of an exception. They are designed to be nominal or opaque. Therefore, you can't compare them with string values.

    However, there are workarounds...

    enum MyEnum {
      foo = 'FOO',
      bar = 'BAR',
    }
    
    type StringIsInEnum = 'FOO' extends `${MyEnum}` ? true : false; // true
    

    TypeScript Playground