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

TypeScript ESLint:回调函数参数触发未使用变量错误的解决方案

解决ESLint未使用变量错误的方案

针对你提供的代码,ESLint标记callFnWithArgs参数中callback的a、b为未使用变量,是因为这两个参数名仅用于定义类型,未在函数体内被直接引用。以下是符合要求的解决办法:

方案1:使用下划线前缀标记未使用的类型参数

ESLint通常允许以下划线开头的变量作为“明确未使用”的约定,既保留类型定义,又不会触发规则:

const callFnWithArgs = (callback: (_a: string, _b: number) => void) =>
  async (a: string, b: number): Promise<void> => {
    try { 
      await callback(a, b)
    } catch(e) {
      console.log(e)
    }
  }

方案2:使用类型别名封装回调函数类型

通过类型别名预先定义回调函数的类型,避免在函数签名中直接写出未使用的参数名:

// 定义回调函数的类型别名
type Callback = (a: string, b: number) => void;

const callFnWithArgs = (callback: Callback) =>
  async (a: string, b: number): Promise<void> => {
    try { 
      await callback(a, b)
    } catch(e) {
      console.log(e)
    }
  }

方案3:利用TypeScript内置工具类型复用参数类型

使用Parameters工具类型提取目标参数的类型组合,同样无需显式写未使用的参数名:

const callFnWithArgs = (callback: (...args: Parameters<(a: string, b: number) => void>) => void) =>
  async (a: string, b: number): Promise<void> => {
    try { 
      await callback(a, b)
    } catch(e) {
      console.log(e)
    }
  }

以上三种方案均满足要求:未禁用ESLint规则、未使用any类型、完整保留了参数类型定义。

内容的提问来源于stack exchange,提问作者Ritik Banger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:05:27