在Yup 1.0.0中的通用枚举解析

huangapple go评论85阅读模式
英文:

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 = &lt;T&gt;(enumObject: { [s: string]: T } | ArrayLike&lt;T&gt;) =&gt;
  Yup.mixed&lt;T&gt;().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 &#39;T&#39; does not satisfy the constraint &#39;AnyPresentValue&#39;

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 = &lt;T extends {}&gt;(
  enumObject: { [s: string]: T } | ArrayLike&lt;T&gt;,
) =&gt; yup.mixed&lt;T&gt;().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 = &lt;T extends string&gt;(
  enumObject: { [s: string]: T } | ArrayLike&lt;T&gt;,
) =&gt; yup.mixed&lt;T&gt;().oneOf(Object.values(enumObject));

huangapple
  • 本文由 发表于 2023年3月3日 18:13:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定