【问题标题】:Use interface as a swagger schema - NestJS DTO使用接口作为招摇模式 - NestJS DTO
【发布时间】:2021-09-28 07:47:38
【问题描述】:

我有以下代码:

import { IsNotEmpty, IsArray, ArrayMinSize } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class PublishDto {
  @IsNotEmpty()
  @IsArray()
  @ArrayMinSize(1)
  @ApiProperty({
    type: [Product]
  })
  products: Product[];
}

interface Product {
  id: string;
  title: string;
  sku: string;
  stock: number;
  description: string;
  shortDescription: string;
  imagesUrl: string[];
  price: number;
  department: string;
  category: string;
  brand: string;
  keywords: string[];
  isActive: boolean;
}

我正在尝试将接口 Product 作为模式放在 swagger 上,但它不起作用,我收到错误消息。 有什么想法吗?

【问题讨论】:

  • 您遇到了什么错误?
  • 我收到代码错误。它无法编译,因为 type 属性不接受 Product 接口。如果你看一下我上传的图片,你会在 ApiProperty 上看到错误。
  • 可以看到有红线表示有错误。请分享错误的实际文本
  • 此错误:错误 TS2693:'Product' 仅指一种类型,但在此处用作值。

标签: swagger nestjs swagger-ui


【解决方案1】:

type 属性需要一个在运行时可用的值,例如实际的 Class 或 Javascript String 类型。接口仅在编译时存在,因此无法以这种方式传递。

如果你想手动传递它,你必须将它转换为一个类,否则你可以看看使用 NestJS Swagger 编译器插件,它使用一些很酷的编译时魔法来自动尝试计算其中的一些东西为你而来

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 2020-02-24
    • 2019-04-01
    • 2022-09-28
    • 2015-08-15
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多