Yup oneOf TypeScript Enum Generic Fucntion

Viewed 3539

I cannot figure out the correct types for a function that generates a yup schema for oneOf with TypeScript enums.


The follow works as expected and has a return type of yup.MixSchema<SomeEnum>

const schema1 = yup.mixed<SomeEnum>().oneOf(Object.values(SomeEnum)); // yup.MixSchema<SomeEnum>

If I try to make a generic function to return the schema I get the return type of yup.MixSchema<typeof SomeEnum>. Notice the typeof.

const oneOfEnum = <T>(enumObject: T) =>
  yup.mixed<T>().oneOf(Object.values(enumObject));

const schema2 = oneOfEnum(SomeEnum); // yup.MixSchema<typeof SomeEnum>

https://codesandbox.io/s/yup-typescript-oneof-enum-vpvjn?file=/src/index.ts

1 Answers

You can fix this like so (change the argument type to match the argument for Object.values):

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