RTK Query用void作查询参数触发@typescript-eslint/no-invalid-void-type错误
解决RTK Query无参数查询的@typescript-eslint/no-invalid-void-type错误
我编写了一个无参数的RTK Query查询函数,代码如下:
endpoints: (build) => ({ fetchEvents: build.query<Test[], void>({ query: () => '/test' }), })
此时ESLint触发错误提示:
void is only valid as a return type or generic type argument
@typescript-eslint/no-invalid-void-type
请问应该用什么类型替代void?
补充说明:我的.eslintrc.js配置如下:
module.exports = { "env": { "browser": true, "es2021": true }, "extends": [ "plugin:react/recommended", "standard-with-typescript", 'eslint:recommended', "prettier" ], "overrides": [ ], "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": "latest", "sourceType": "module", "project": "./tsconfig.json", }, "plugins": [ "react", "@typescript-eslint", "prettier" ], "rules": { "@typescript-eslint/consistent-type-definitions": ["error", "type"], }, "settings": { "react": { "version": "detect", }, } }
解决方案
用undefined替代void作为泛型的参数类型即可,修改后的代码:
endpoints: (build) => ({ fetchEvents: build.query<Test[], undefined>({ query: () => '/test' }), })
原因:@typescript-eslint/no-invalid-void-type规则禁止将void用作泛型参数(仅允许作为返回类型),而undefined是合法的类型,能准确表示该查询不需要传入任何参数,RTK Query完全支持这种写法。
如果不想修改代码,也可以在ESLint配置中给该规则添加例外,但更推荐遵循TypeScript规范使用undefined,保证代码风格统一。
内容的提问来源于stack exchange,提问作者mahan
相关产品推荐
相关产品推荐

