NestJS 将主体参数强制为基于类型的值

NestJS Force body parameter to values based on type

首先,我问这个只是因为我没有找到适合这种情况的答案另外我刚刚开始学习 NestJS。

我有以下声明:

// Type definition of options
type Gender = "Male" | "Female";

// DTO
export class User {
    ...
    gender: Gender;
}

// Inside controller
...
@Post()
registerUser(@Body() data: User) {
    console.log(data.gender);
}
...

不幸的是,如果它在正文中将性别设置为“未知”,它将是 data.gender 的值,即使它不在允许的值区间内。我想将值限制为类型定义中唯一可用的值。我在枚举中看到了如何做到这一点的例子,但在类型上看到了 none 。 是否可以使用类型来限制它们?

npm i --save class-validator class-transformer

在 main.ts

中进行更改
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());  <= add this
  await app.listen(3000);
}
bootstrap();

然后像这样尝试

import { IsDefined, IsIn, IsNotEmpty } from 'class-validator';

// DTO
export class User {
    ...

    @IsDefined()
    @IsNotEmpty()
    @IsIn(['Male','Female'])
    gender: Gender;
}

// Inside controller
...
@Post()
registerUser(@Body() data: User) {
    console.log(data.gender);
}
...