简体   繁体   English

这是最佳实践吗? 检查变量是否定义或分配 null

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

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.基本上,如果未定义属性图片,我不应该使用 filesService 中的服务查找,因为如果属性图片是 null 或未定义,typeORM 将返回它找到的第一个值。

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.但是 TS 会抱怨,因为我在 If 中声明了一个变量。

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如果您只想在设置updateUserDto?.picturepictureEntity设置为一个值,那么您最初的尝试几乎是正确的,但您只需要在if块之外定义变量,然后再像这样设置值

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.请注意,您需要使用let而不是const ,因为您现在要在创建后分配给变量。 Also note that the default value of pictureEntity will be undefined if updateUserDto?.picture is falsy另请注意,如果updateUserDto?.picture为 falsy, pictureEntity的默认值将undefined

You could do:你可以这样做:

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

If updateUserDto is null or undefined , pictureEntity will be undefined .如果updateUserDtonullundefinedpictureEntity将是undefined Otherwise it will await your other promise.否则它将await您的其他 promise。

Edit:编辑:

There's also no need for a const here:这里也不需要const

if (pictureEntity) {

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

}

You don't use const to create object properties.您不使用const创建 object 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM