Is this best practice? Checking if variable defined or assign null

154 Views Asked by At
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

There are 2 best solutions below

0
On BEST ANSWER

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.

1
On

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