Search code examples
typescriptvalidationenumsyup

generic enum parsing in yup 1.0.0


we are currently on yup 0.32.11. in order to create a generic enum parser, we have been using the following

export const oneOfEnum = <T>(enumObject: { [s: string]: T } | ArrayLike<T>) =>
  Yup.mixed<T>().oneOf(Object.values(enumObject));

this was taken from this question Yup oneOf TypeScript Enum Generic Fucntion, but no longer works in the newest version of yup

with 1.0.0, this shows the error: Type 'T' does not satisfy the constraint 'AnyPresentValue'

I cannot figure out the proper incantation for this...part of this is that I'm not really sure how to represent enums in typescript's generics


Solution

  • If you look into yup type definitions, you can see that generic argument of yup.mixed must extend AnyPresentValue type, which is an alias for {} type.

    Solution would be to also mark your generic parameter as extending {}:

    export const oneOfEnum = <T extends {}>(
      enumObject: { [s: string]: T } | ArrayLike<T>,
    ) => yup.mixed<T>().oneOf(Object.values(enumObject));
    

    If you want to be more strict and match your enum values more closely, you can use string instead of {} (or number, depends on your enum values).

    export const oneOfEnum = <T extends string>(
      enumObject: { [s: string]: T } | ArrayLike<T>,
    ) => yup.mixed<T>().oneOf(Object.values(enumObject));