0
const pictureEntity = updateUserDto?.picture

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

  : null;

if (pictureEntity) {

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

}

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

我正在这样做:

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

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

4

2 回答 2

1

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

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

请注意,您将需要使用let而不是,const因为您现在在创建后分配给变量。另请注意,默认值pictureEntitywill 是undefinedifupdateUserDto?.picture是 falsy

于 2021-05-07T15:18:27.500 回答
0

你可以这样做:

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创建对象属性。

于 2021-05-07T15:18:57.340 回答