我有这样的开胃小吃.

export enum Status {
  Active = "Active",
  Inactive = "Inactive",
}

我有这样的UserStatus

export enum UserStatus {
  Active = Status.Active,
};

我有一个共同的目标,那就是

export class CommonDto {

  @ApiProperty({ description: "Status", required: true })
  status: Status;

在我的用户dto中,我扩展了这个类,就像这样

export class UserDto extends CommonDto {

  @ApiProperty({ description: "Status", required: true, enum: UserStatus })
  status: UserStatus;

但这是在显示错误

Property 'status' in type 'UserDto' is not assignable to the same property in base type 'CommonDto'.
  Type 'UserStatus' is not assignable to type 'Status'

有什么帮助吗?

推荐答案

有一些方法可以解决这个问题.

第一条路;泛型类

在本例中,我们设置了status通用的类型.因此,您可以 for each 从CommonD扩展到OWN类型的类指定状态.

export class CommonDto<T> {
  @ApiProperty({ description: "Status", required: true })
  status: T;
  // ...
}

export class UserDto extends CommonDto<UserStatus> {
  // ...
}

第二种方式:联合类型

您可以在文字稿中设置多种可能的类型,如下所示:

export type AnyStatus = Status | UserStatus;

export class CommonDto {
  @ApiProperty({ description: "Status", required: true })
  status: AnyStatus;
  // ...
}

export class UserDto extends CommonDto {
  @ApiProperty({ description: "Status", required: true, enum: UserStatus })
  status: AnyStatus;
  // ...
}

第三种方法:使用交集类型

在TypeScrip中,您可以在扩展类中"删除"和"添加"属性,以调整其类型,如下所示:

type WithUserStatus<T> = Omit<T, 'status'> & { status: UserStatus };

type UserDto = WithUserStatus<CommonDto>;

关于拼写的更多Read

These are the options you have to go. In your case I would set status in each class (except the base class (CommonDto)) separately with its own type.

Node.js相关问答推荐

在child_Process中持久运行SSH命令

Spotify Auth访问令牌给出错误代码400

利用Gemini:通过Vertex AI还是通过Google/generative-ai?

即使DDB键不存在, node Lambda也不会失败,并返回NULL作为结果

JsonwebToken过期后如何注销和清除cookie?

无法使用NPM安装REDUX和DATEPPICER

模块';"; node :流程&没有导出的成员';dlopen';

PM2 是否需要成为其托管项目的依赖项?

错误 node :错误:绑定消息提供 16 个参数,但准备语句需要 15 个

级联定时器和Jest 的异步功能

Discord.js V14 interaction.editReply 给出了一个无效的 webhook 令牌错误

使用中的端口代码:'EADDRINUSE',即使在 kill 命令之后

如何在 Node.js 中逐字节读取二进制文件

使 pm2 登录到控制台

从 CoffeeScript 中的数组中删除一个值

在多个 .env 文件之间切换,例如 .env.development 和 node.js

使用 NodeJS 将新对象附加到 DynamoDB 中的 JSON 数组

User.findOrCreate 函数是做什么的,什么时候在Passport 中调用它?

遍历 NodeJS 中的一系列日期

使用 node.js 循环 JSON