TypeScript数组字段重命名时修复SonarQube临时变量报错
问题描述
现有数据库查询代码如下:
const whiteListUrls = await this.whiteListDomainsRepository.find({ where: {and: [{isActive: true}, {type: 'redirect'}]}, });
查询返回的whiteListUrls为WhiteListDomain类型的实体数组,结构示例:
[ WhiteListDomain { whiteListDomainId: '62b068307bed2ef2c57c4bbf', domain: 'go.pampers.com', isActive: true, type: 'redirect', createdDate: 2021-03-25T06:11:53.974Z, createdBy: 'thakkar.dt.1@pg.com', updatedBy: 'thakkar.dt.1@pg.com', updatedDate: 2021-03-25T06:13:53.545Z }, WhiteListDomain { whiteListDomainId: '62b068f87bed2ef2c57c4bc0', domain: 'app.adjust.com', isActive: true, type: 'redirect', createdDate: 2021-03-25T06:11:53.974Z, createdBy: 'thakkar.dt.1@pg.com', updatedBy: 'thakkar.dt.1@pg.com', updatedDate: 2021-03-25T06:13:53.545Z } ]
需求为将返回结果中的whiteListDomainId字段重命名为id,由于whiteListUrls是数据库查询直接返回的实体实例,无法直接覆写原变量。原有实现触发了SonarQube规则报错:"Immediately return this expression instead of assigning it to the temporary variable",即要求避免无意义的临时变量赋值,直接返回表达式结果。
原有问题代码:
interface GetWhiteListesdUrls { id: string; domain: string; isActive: boolean; type: string; createdDate: string; createdBy: string; updatedDate: string; updatedBy: string; } const urls = whiteListUrls.map(element => { const obj: GetWhiteListesdUrls = { id: element.whiteListDomainId!, domain: element.domain, isActive: element.isActive!, type: element.type, createdDate: element.createdDate, createdBy: element.createdBy, updatedDate: element.updatedDate, updatedBy: element.updatedBy, }; return obj; }); return urls;
解决方案
SonarQube报错的核心原因是代码中创建了两个仅单次使用的临时变量urls和obj,属于冗余代码,完全可以省略。
方案1:直接返回map结果(最小改动,符合代码规范)
移除所有多余临时变量,直接返回map执行结果,同时给map回调添加明确的返回值类型,强化TS类型校验:
// 修正原接口拼写错误:WhiteListesd -> Whitelisted interface GetWhitelistedUrls { id: string; domain: string; isActive: boolean; type: string; createdDate: Date; // 修正原类型错误:查询返回的是Date对象,不是string createdBy: string; updatedDate: Date; updatedBy: string; } return whiteListUrls.map((element): GetWhitelistedUrls => ({ id: element.whiteListDomainId!, domain: element.domain, isActive: element.isActive!, type: element.type, createdDate: element.createdDate, createdBy: element.createdBy, updatedDate: element.updatedDate, updatedBy: element.updatedBy, }));
该写法完全符合SonarQube规则,没有冗余变量,类型安全。
方案2:ORM层直接配置字段别名(更优方案,减少性能损耗)
如果使用TypeORM等支持字段映射的ORM框架,可以直接在查询阶段配置字段别名,不需要业务层遍历数组做转换,执行效率更高:
// TypeORM 写法示例 return this.whiteListDomainsRepository.find({ select: { whiteListDomainId: 'id', // 查询阶段直接将字段重命名为id domain: true, isActive: true, type: true, createdDate: true, createdBy: true, updatedDate: true, updatedBy: true, }, where: {and: [{isActive: true}, {type: 'redirect'}]}, }) as Promise<GetWhitelistedUrls[]>;
额外优化建议
- 代码中使用的非空断言
!建议谨慎使用,如果数据库层面whiteListDomainId、isActive为非空字段,可以直接在ORM实体定义中标记为非空,不需要每次使用都加断言 - 接口命名注意拼写校验,避免无意义的拼写错误增加后续维护成本
内容的提问来源于stack exchange,提问作者MochaTesty
相关产品推荐
相关产品推荐

