You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:45:37