英文:
generic enum parsing in yup 1.0.0
问题
我们目前使用的是Yup 0.32.11版本。为了创建一个通用的枚举解析器,我们一直在使用以下代码:
export const oneOfEnum = <T>(enumObject: { [s: string]: T } | ArrayLike<T>) =>
Yup.mixed<T>().oneOf(Object.values(enumObject));
这段代码是从这个问题 https://stackoverflow.com/questions/62177877/yup-oneof-typescript-enum-generic-fucntion 中获取的,但在最新版本的Yup中不再起作用。
在1.0.0版本中,这会显示错误:Type 'T' does not satisfy the constraint 'AnyPresentValue'
。
我无法弄清楚这个的正确用法...部分原因是我不太确定如何在TypeScript的泛型中表示枚举。
英文:
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 https://stackoverflow.com/questions/62177877/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
答案1
得分: 2
如果您查看yup类型定义,您会看到yup.mixed
的通用参数必须扩展AnyPresentValue
类型,这是{}
类型的别名。
解决方案是将您的通用参数也标记为扩展{}
:
export const oneOfEnum = <T extends {}>(
enumObject: { [s: string]: T } | ArrayLike<T>,
) => yup.mixed<T>().oneOf(Object.values(enumObject));
如果您希望更加严格地匹配枚举值,可以使用string
代替{}
(或者根据您的枚举值使用number
)。
export const oneOfEnum = <T extends string>(
enumObject: { [s: string]: T } | ArrayLike<T>,
) => yup.mixed<T>().oneOf(Object.values(enumObject));
英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论