【问题标题】:Class Validators are not working when the type is a Record <k,v> - NestJS当类型是 Record <k,v> - NestJS 时,类验证器不起作用
【发布时间】:2022-01-17 18:55:15
【问题描述】:

我们有一个 DTO 属性,它的类型是 Record&lt;string, Animal&gt;Animal 是另一个带有类验证器的 DTO,例如 @IsDefined()、@IsNotEmpty()。然而,这些验证没有按预期工作,这可能是因为它具有 Record 类型。

我已经尝试添加@ValidatedNested({ each: true }),但仍然没有成功。我们怎样才能使Animal dto 在Record&lt;string, Animal&gt; 中的验证工作?

【问题讨论】:

  • typescript world:类型在运行时被擦除,这就是为什么你不能依赖Record type。我不使用class-validator,所以我帮不了你。
  • 您可以将您的控制器和 dto(所有您的 dto)添加到您的帖子中吗?
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: javascript typescript nestjs typescript-typings class-validator


【解决方案1】:

您可以尝试构建部分类验证器,https://trilon.io/blog/introducing-mapped-types-for-nestjs 这是一些文档。 例如:

export class Record extends PartialType(
  OmitType(Animal , ['legs'] as const),
) {}

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 2021-02-03
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多