最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - NestJS Return Array of Arrays - Stack Overflow

programmeradmin0浏览0评论

I have an endpoint (which I didn't design) that returns an array of arrays, and I want to properly represent it using @nestjs/swagger. Additionally, I’d like to use the DTO as a Type throughout my code.

It seems impossible to define an array-of-arrays structure using a DTO, but it also feels like it would be a common enough case that there might be a clever solution I haven't found yet.

Here is my controller + DTO as close as I can get it:

import { Controller, Get } from '@nestjs/common';
import { ApiOkResponse, ApiProperty } from '@nestjs/swagger';

class ExampleDto {
  @ApiProperty({ isArray: true })
  0: RealApiReturnType[number];
  [key: number]: RealApiReturnType[number];
}

type RealApiReturnType = [string[], string];

@Controller()
export class AppController {
  @Get()
  @ApiOkResponse({
    type: ExampleDto,
    isArray: true,
  })
  getHello(): RealApiReturnType {
    // @ts-expect-error Type 'ExampleDto' is not assignable to type 'RealApiReturnType' ts(2322)
    return [['Bad', 'Design'], 'I know'] as ExampleDto;
  }
}

Issues:

  1. Type Mismatch: Type 'ExampleDto' is not assignable to type 'RealApiReturnType'.
  2. Incorrect Swagger Output: The response schema incorrectly includes an object instead of a true array-of-arrays.

For context, the real return type I need to support is more complex, but I’ve simplified it to [string[], string] for this example:

export type IrlDto = readonly [
  readonly (readonly [`${string}:${string}`, string, `${number}`, number])[],
  readonly ['COLUMN', 'ROW', 'ID', 'AVAILABLE'],
];

Is there a way to properly define this in @nestjs/swagger, or am I stuck with an incompatible design?

发布评论

评论列表(0)

  1. 暂无评论