0
const pictureEntity = updateUserDto?.picture

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

  : null;

if (pictureEntity) {

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

}

Is this the correct way to assign the value to pictureEntity? Basically if property picture is not defined, I'm not supposed to use the service find in filesService because typeORM will return the first value that it finds if property picture is null or undefined.

I was doing this:

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

but TS would complain because I'm declaring a variable inside an If.

2 Answers2

1

If you want to set pictureEntity to a value only when updateUserDto?.picture is set, your original attempt was almost correct but you just need to define the variable outside of the if block before setting the value like this

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

Be aware that you will need to use let instead of const since you're now assigning to the variable after creation. Also note that the default value of pictureEntity will be undefined if updateUserDto?.picture is falsy

Ben Watson
  • 31
  • 2
  • Yes, I thought of that! But I didn't want to declare and then use, because I'm using that value elsewhere, And I know for a fact that picture entity will be undefined if there is none – Uriel Nicolas May 07 '21 at 17:49
0

You could do:

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

If updateUserDto is null or undefined, pictureEntity will be undefined. Otherwise it will await your other promise.

Edit:

There's also no need for a const here:

if (pictureEntity) {

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

}

You don't use const to create object properties.

MinusFour
  • 13,913
  • 3
  • 30
  • 39