#Is it possible to restrict an enum's value type?

3 messages · Page 1 of 1 (latest)

unkempt pike
#

We can define enum's with string, number, or mixed values. Can we restrict an enum's value type to one or the other, or even none?

E.g.,

// Specify values as strings.
enum MyEnum {
  VALUE1 = 'hello',
  VALUE2 = 42 // Error.
}
vocal timber
#

@unkempt pike AFAIK, no. But you could use a const object instead of an enum for a similar effect:

sand loomBOT
#
const MyEnum = {
  VALUE1: 'hello',
  VALUE2: 42 // Error.
} as const satisfies Record<string, string>;
//                   ^^^^^^^^^^^^^^^^^^^^^^
// Type '{ readonly VALUE1: "hello"; readonly VALUE2: 42; }' does not satisfy the expected type 'Record<string, string>'.
//   Property 'VALUE2' is incompatible with index signature.
//     Type 'number' is not assignable to type 'string'.