【问题标题】:How to extend more than one dto class in Nestjs如何在 Nestjs 中扩展多个 dto 类
【发布时间】:2021-04-01 19:57:51
【问题描述】:

我是nest.js 的新手,对此有疑问。

我想将多个Dto 扩展到我的主要dto 类,但我知道不能扩展超过2 个dto 类。你知道怎么做吗?

这是我的主要dto 课程:

export class CarDto extends PickupLocationDto {
  @ApiProperty({ example: 'Aventador', description: 'The car name' })
  readonly modelName: string;
}

最近我只能从PickupLocationDto 类扩展它,但我想再扩展一个dto 类到这个CarDto 类。

感谢任何帮助。

【问题讨论】:

  • 请记住 ValidationPipe 不适用于 entend 类属性。

标签: javascript node.js typescript nestjs


【解决方案1】:

由于我使用 swagger,所以使用 @nestjs/mapped-types 包不会显示相交 dto 中的所有变量。因此,我使用 swagger 中的 IntersectionType

import { ApiProperty, IntersectionType } from '@nestjs/swagger';

export class Dto3 extends IntersectionType(
  Dto1,
  Dto2,
) {}

【讨论】:

    【解决方案2】:

    您可以使用 mapped-types 来执行此操作,首先您需要安装软件包 (yarn add @nestjs/mapped-types),然后使用 IntersectionType,如下所示:

    import { IntersectionType } from '@nestjs/mapped-types';
    
    export class Dto3 extends IntersectionType(
      Dto1,
      Dto2,
    ) {}
    

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 2021-07-24
      • 2021-05-08
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2012-10-18
      相关资源
      最近更新 更多