Angular项目中如何用ESLint检测TypeScript方法缺失的return语句?
问题解答:Angular/TypeScript项目中检测函数分支遗漏return的ESLint规则
你的项目使用以下ESLint相关依赖:
"@angular-eslint/builder": "14.0.2", "@angular-eslint/eslint-plugin": "14.0.2", "@angular-eslint/eslint-plugin-template": "14.0.2", "@angular-eslint/schematics": "14.0.2", "@angular-eslint/template-parser": "14.0.2", "@typescript-eslint/eslint-plugin": "5.29.0", "@typescript-eslint/parser": "5.29.0", "eslint": "^7.32.0", "eslint-config-prettier": "^8.5.0", "eslint-plugin-import": "2.26.0", "eslint-plugin-jsdoc": "39.3.3", "eslint-plugin-prefer-arrow": "1.2.3",
你已启用@typescript-eslint/explicit-function-return-type规则,但该规则无法检测到如下代码中try块遗漏return的问题:
private receivedDataFromServer(state: MyState, data: ServerData[]): MyState { const methodName = `${moduleName}.receivedDataFromServer`; try { // 此处未编写return语句,且无错误提示 } catch (error) { this.logger.error(`${methodName}): ${Utils.unknownTypeToString(error)}`); return state; } }
问题原因
@typescript-eslint/explicit-function-return-type仅负责强制显式声明函数返回类型,不检查函数的所有代码路径是否都返回了符合类型要求的值。
解决方案:启用@typescript-eslint/consistent-return规则
该规则会检查函数的所有分支是否保持一致的return行为——要么所有分支都返回值,要么都不返回,能精准捕获你代码中遗漏return的场景。
配置方式
在ESLint配置文件(如.eslintrc.json)中添加规则:
{ "rules": { "@typescript-eslint/consistent-return": "error" } }
额外建议
除了ESLint规则,你还可以开启TypeScript编译器的noImplicitReturns选项,在编译阶段就检测这类代码路径问题:
// tsconfig.json { "compilerOptions": { "noImplicitReturns": true } }
内容的提问来源于stack exchange,提问作者peterc
相关产品推荐
相关产品推荐

