superstruct icon indicating copy to clipboard operation
superstruct copied to clipboard

Native Typescript enum support

Open 03xb7 opened this issue 4 years ago • 3 comments

Hello, is there a way to express that some struct field must be of a given TS enum type ?

enum MyEnum {
  Value1 = 'val1',
  Value2 = 'val2',
}

const MyStruct = object({
   // Something like this:
   myEnum: nativeEnum(MyEnum)
})

// Here the MyStruct type would have a myEnum key of type MyEnum
type MyStruct = Infer<typeof MyStruct>;

Thanks

03xb7 avatar Jan 04 '22 13:01 03xb7

So for a string enum, one can do:

const MyStruct = object({
   myEnum: enums(Object.values(MyEnum))
})

But for numeric enums it does not work

03xb7 avatar Jan 04 '22 16:01 03xb7

@htulipe this is an interesting idea. I'd be open to a PR that supported native enum-shaped objects as the config parameter for enums.

ianstormtaylor avatar Mar 02 '22 16:03 ianstormtaylor

any update on that? 🙏

szygendab avatar Jun 16 '26 12:06 szygendab