1

Is below a valid use of an enum in an interface?

declare enum MyEnumType {
   Member1,
   Member2,
}
interface Foo {
  prop1: MyEnumType,          // this is valid
  prop2: MyEnumType.Member1   // how about this? If not, why?
}

1 Answer 1

1

If you run this code in a sandbox, you will get an Error:

Enum type 'MyEnumType' has members with initializers that are not literals.

It is invalid only if you declare the enum. In this case you tell TS that enum exists, but you don't tell it what are it's values, because the definition of this enum could be like this:

enum MyEnumType {
  Member1 = 8,
  Member2 = 'RaNdOmWhAtEvEr'
}

This means MyEnumType.Member2 is ambiguous. It will works if you

  1. Define enum explicitly (remove declare keyword). Now TypeScript is in full control of the enum and it knows it will assign values 0 and 1 to its keys
  2. Explicitly tell, what are the keys of the declared enum
declare enum MyEnumType {
  Member1 = 0,
  Member2 = 1
}

Now TS knows what to expect from the enum and is able to operate with its keys as types.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.