这是最佳做法吗?检查变量是否定义或分配为空

问题描述

const pictureEntity = updateUserDto?.picture

  ? await this.filesService.find(updateUserDto.picture)

  : null;

if (pictureEntity) {

  const pictureEntity.url = await this.filesService.getFileUrl(pictureEntity);

}

这是将值分配给 pictureEntity 的正确方法吗?基本上,如果未定义属性图片,我不应该使用 filesService 中的服务 find,因为如果属性图片为 null 或未定义,typeORM 将返回它找到的第一个值。

我是这样做的:

if (updateUserDto?.picture) {
  const pictureEntity = await this.filesService.find(updateUserDto.picture);
}

但是 TS 会抱怨,因为我在 If 中声明了一个变量。

解决方法

如果您只想在设置 pictureEntity 时将 updateUserDto?.picture 设置为一个值,您最初的尝试几乎是正确的,但您只需要在 if 块之外定义变量像这样设置值

let pictureEntity;
if (updateUserDto?.picture) {
  pictureEntity = await this.filesService.find(updateUserDto.picture);
}

请注意,您将需要使用 let 而不是 const,因为您现在要在创建后分配给变量。另请注意,如果 pictureEntity 为假

undefined 的默认值为 updateUserDto?.picture ,

你可以这样做:

const pictureEntity = updateUserDto?.picture && await this.filesService.find(updateUserDto.picture);

如果 updateUserDtonullundefinedpictureEntity 将是 undefined。否则它会await你的另一个承诺。

编辑:

这里也不需要 const

if (pictureEntity) {

  const pictureEntity.url = await this.filesService.getFileUrl(pictureEntity);

}

您不使用 const 创建对象属性。