最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

Typescript装饰器混乱

IT培训 admin 0浏览 0评论

Typescript装饰器混乱

是否有办法解决类内部大量使用装饰器的问题?

这是我的NestJS应用程序中类的single属性的示例,带有incomplete swagger文档装饰器:

  @ApiModelProperty({
    description: 'description',
  })
  @Expose()
  @MaxLength(100, { message: 'message' })
  @IsString({ message: 'message' })
  @ValidateIf(address=> address.id !== null)
  @NotEquals(undefined, { message: 'message' })
  address: string;

这很快就变得庞大而丑陋。有什么方法可以使代码看起来更简洁,在另一个文件中定义装饰器?

回答如下:

装饰器是常规的打字稿功能。您可以尝试将多个装饰器组合为一个装饰器。例如,您可以将验证者混合到单个装饰器中,如下所示:

function apiStringField(maxLength: number, message: string, description?: string) {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) { 
      ApiModelProperty()(target, propertyKey, descriptor)
      Expose()(target, propertyKey, descriptor)
      MaxLength(maxLength, { message })(target, propertyKey, descriptor) 
      IsString({ message })(target, propertyKey, descriptor)
      NotEquals(undefined, { message })(target, propertyKey, descriptor) 
  }
}

并且,像这样使用它(在导入之后:):

@apiStringField(100, 'message', 'description')
address: string;

Typescript装饰器混乱

是否有办法解决类内部大量使用装饰器的问题?

这是我的NestJS应用程序中类的single属性的示例,带有incomplete swagger文档装饰器:

  @ApiModelProperty({
    description: 'description',
  })
  @Expose()
  @MaxLength(100, { message: 'message' })
  @IsString({ message: 'message' })
  @ValidateIf(address=> address.id !== null)
  @NotEquals(undefined, { message: 'message' })
  address: string;

这很快就变得庞大而丑陋。有什么方法可以使代码看起来更简洁,在另一个文件中定义装饰器?

回答如下:

装饰器是常规的打字稿功能。您可以尝试将多个装饰器组合为一个装饰器。例如,您可以将验证者混合到单个装饰器中,如下所示:

function apiStringField(maxLength: number, message: string, description?: string) {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) { 
      ApiModelProperty()(target, propertyKey, descriptor)
      Expose()(target, propertyKey, descriptor)
      MaxLength(maxLength, { message })(target, propertyKey, descriptor) 
      IsString({ message })(target, propertyKey, descriptor)
      NotEquals(undefined, { message })(target, propertyKey, descriptor) 
  }
}

并且,像这样使用它(在导入之后:):

@apiStringField(100, 'message', 'description')
address: string;

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论