Create React App项目中noImplicitAny规则不生效问题求助
问题原因与解决方案
为什么response.json()的any没触发错误?
TypeScript的noImplicitAny规则仅针对代码中隐式推断出的any类型(比如未指定类型的函数参数、未初始化的变量等)。而fetch API的response.json()方法在TypeScript的DOM类型定义(lib.dom.d.ts)中是**显式声明为返回Promise<any>**的,这种来自类型定义的显式any不会被noImplicitAny规则检测到,所以编译器不会报错。
解决方法
方法1:为响应数据定义类型(推荐)
手动定义接口约束API返回的JSON结构,通过类型断言或泛型将response.json()的结果转换为指定类型,既解决any问题,又获得类型提示:
// 定义API响应的结构接口 interface ApiResponse { categories: string[]; // 根据实际返回字段调整类型 } async function fetchCategories() { try { const response = await fetch('some-url'); if (response.ok) { // 断言为自定义类型 const jsonResult = await response.json() as ApiResponse; return jsonResult?.categories; } throw new Error('Fetching failed'); } catch (error) { console.error(error); return []; } }
更优雅的方式是封装泛型fetch工具函数:
async function fetchJson<T>(url: string): Promise<T> { const response = await fetch(url); if (!response.ok) { throw new Error(`Request failed with status ${response.status}`); } return response.json() as Promise<T>; } // 使用时指定类型 async function fetchCategories() { try { const jsonResult = await fetchJson<ApiResponse>('some-url'); return jsonResult?.categories; } catch (error) { console.error(error); return []; } }
方法2:通过ESLint检测不安全的any使用
如果想检测所有any类型的使用(包括来自类型定义的显式any),可以启用@typescript-eslint的相关规则,在package.json的eslintConfig.rules中添加:
"rules": { // 保留原有规则 "@typescript-eslint/no-explicit-any": 2, "jsdoc/require-returns": 0, "jsdoc/check-tag-names": 0, "padded-blocks": 0, // 新增检测规则 "@typescript-eslint/no-unsafe-assignment": 2, "@typescript-eslint/no-unsafe-member-access": 2 }
这些规则会在你将any类型赋值给变量、或访问any类型属性时触发报错,强制你处理any类型。
内容的提问来源于stack exchange,提问作者Surender Thakran
相关产品推荐
相关产品推荐

