TypeScript检查未定义变量代码冗余,如何优化实现?
优化方案
针对你当前逐个检查属性是否存在的冗余代码,这里提供几种TypeScript下的更优实现:
1. 数组every批量检查(最通用的简化方式)
把需要验证的属性放进数组,用every方法一次性判断所有属性是否符合要求,适合属性数量较多的场景:
const { firstId, secondId, thirdId } = bigObject || {}; // 若要过滤所有假值(和原代码逻辑一致,0、''等也会被排除),用every(Boolean) // 若仅排除undefined和null,用every(id => id != null) if ([firstId, secondId, thirdId].every(id => id != null)) { api.doStuff({ firstId, secondId, thirdId }).then(res => console.log(res)); }
2. 结合可选链与对象完整性检查
利用TypeScript的可选链语法简化属性获取,再配合every检查对象属性:
const targetProps = bigObject?.{ firstId, secondId, thirdId }; // 确保对象存在且所有属性都不为undefined/null if (targetProps && Object.values(targetProps).every(val => val != null)) { api.doStuff(targetProps).then(res => console.log(res)); }
3. 类型约束减少运行时检查(TypeScript专属优势)
如果可以在类型层面约束bigObject,当它存在时必然包含三个非空的ID属性,就能省去部分运行时检查:
// 定义包含非空ID的类型 interface RequiredIds { firstId: string | number; // 根据实际类型调整,用NonNullable<T>确保非空 secondId: string | number; thirdId: string | number; } // 假设bigObject的类型是RequiredIds | undefined if (bigObject) { // TypeScript会推断bigObject的三个属性都非空,无需额外检查 api.doStuff(bigObject).then(res => console.log(res)); }
注意:这种方式依赖类型定义的准确性,若运行时数据可能不符合类型约束,仍需保留运行时兜底检查。
4. 格式简化(适合属性数量少的场景)
如果只是觉得换行导致的冗余,可将条件合并为一行,逻辑和原代码完全一致:
const { firstId, secondId, thirdId } = bigObject || {}; firstId && secondId && thirdId && api.doStuff({ firstId, secondId, thirdId }).then(res => console.log(res));
内容的提问来源于stack exchange,提问作者Cjmaret
相关产品推荐
相关产品推荐

