关于@typescript-eslint/no-unnecessary-condition误报的技术咨询
问题解答
你的理解是正确的
你对timedOut变量的逻辑判断没有问题:当locator.waitFor()超时失败时,catch回调会将timedOut修改为true,因此这个变量并非始终为假值。
ESLint警告的原因
@typescript-eslint/no-unnecessary-condition规则依赖静态代码分析,它无法追踪异步回调函数对外部变量的修改。虽然你的代码逻辑是成立的,但静态分析工具没办法识别catch箭头函数里的变量变更,因此误判timedOut始终保持初始的false值。
解决方法
方法1:临时禁用该行规则
在触发警告的代码行上方添加注释,直接跳过该规则的检查:
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition return [timedOut ? -1 : index, locator];
方法2:重构代码为try/catch结构
改用try/catch替代链式调用的.catch(),让ESLint更容易识别变量的修改逻辑:
async function waitForOneOf(locators: Locator[]): Promise<WaitForRes> { const timeToWait = 5000; const res = await Promise.race([ ...locators.map(async (locator, index): Promise<WaitForRes> => { let timedOut = false; try { await locator.waitFor({ state: 'visible', timeout: timeToWait }); } catch { timedOut = true; } return [timedOut ? -1 : index, locator]; }), ]); if (res[0] === -1) { throw new Error(`no locator visible before timeout ${locators.toString()}`); } return res; }
方法3:直接通过Promise结果赋值
将waitFor的结果转换为布尔值,直接赋值给timedOut,避免外部变量修改的逻辑:
async function waitForOneOf(locators: Locator[]): Promise<WaitForRes> { const timeToWait = 5000; const res = await Promise.race([ ...locators.map(async (locator, index): Promise<WaitForRes> => { const timedOut = !(await locator.waitFor({ state: 'visible', timeout: timeToWait }).catch(() => false)); return [timedOut ? -1 : index, locator]; }), ]); if (res[0] === -1) { throw new Error(`no locator visible before timeout ${locators.toString()}`); } return res; }
内容的提问来源于stack exchange,提问作者Patrick Kenny
相关产品推荐
相关产品推荐

