ESLint提示TypeScript函数未使用变量问题求助
数组删除工具函数的TS类型与ESLint问题解决
我编写了一个修改原数组的元素删除工具函数,用法如下:
removeArrayItem(myArray, (item) => item.name === 'johhny')
但遇到两个问题:
- 将
callback类型设为Function时,TypeScript提示类型不匹配 - 定义完整
callback类型后,ESLint提示value、index、obj未被使用,换成下划线也无法解决
三次尝试及问题
第一次尝试
Type 'Function' provides no match for the signature '(value: any, index: number, obj: any[]): unknown'.ts(2345)
const removeArrayItem = (array: any[], callback: Function) => { const index = array.findIndex(callback) if (index > -1) array.splice(index, 1) }
第二次尝试
'value' is defined but never used. eslint no-unused-vars, 'index' is defined but never used. eslint no-unused-vars, 'obj' is defined but never used. eslint no-unused-vars,
const removeArrayItem = (array: any[], callback: (value: any, index: number, obj: any[]) => unknown) => { const index = array.findIndex(callback) if (index > -1) array.splice(index, 1) }
第三次尝试(结果与第二次相同)
const removeArrayItem = (array: any[], callback: (_: any, __: number, __: any[]) => unknown) => { const index = array.findIndex(callback) if (index > -1) array.splice(index, 1) }
解决方案
1. 修复TypeScript类型不匹配问题
不要用宽泛的Function类型,直接复用数组findIndex方法的回调签名,同时用泛型支持任意类型数组:
const removeArrayItem = <T>(array: T[], callback: Parameters<Array<T>['findIndex']>[0]) => { const index = array.findIndex(callback) if (index !== -1) { array.splice(index, 1) } }
<T>泛型让函数适配任意类型的数组,避免any带来的类型不安全Parameters<Array<T>['findIndex']>[0]直接获取findIndex的回调参数类型,完美匹配TS的类型要求
2. 解决ESLint未使用变量问题
问题出在ESLint对下划线变量的匹配规则,多数默认配置只忽略单个下划线的变量,双下划线__不会被识别。
调整调用方式
如果调用时不需要index或数组本身,直接只写需要的参数即可;如果需要写全参数但只用第一个,把未使用的参数换成单个下划线:
// 只用到第一个参数 removeArrayItem(myArray, (item) => item.name === 'johhny') // 写全参数但忽略后续参数 removeArrayItem(myArray, (item, _) => item.name === 'johhny')
调整ESLint配置(可选)
如果需要支持多个下划线的变量,在ESLint配置文件中修改规则:
module.exports = { rules: { // 针对普通JS文件 "no-unused-vars": ["error", { "varsIgnorePattern": "^_+$" }], // 针对TypeScript文件(如果使用@typescript-eslint) "@typescript-eslint/no-unused-vars": ["error", { "varsIgnorePattern": "^_+$" }] } }
该配置会忽略所有由下划线组成的变量(_、__、___等)。
内容的提问来源于stack exchange,提问作者Martin Zeltin
相关产品推荐
相关产品推荐

