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

TypeScript不可变移除数组首元素如何避免@typescript-eslint/no-unused-vars报错

最优方案:使用Array.prototype.slice

slice本身是不可变操作,不会修改原数组,传入起始索引1即可直接返回移除第一个元素后的新数组,没有冗余变量,也不会触发TS/eslint报错:

function getArray(): number[] {
   return [1, 2, 3, 4, 5];
}
function getAnother(): number[] {
  // slice(1) 从索引1开始拷贝到数组末尾,返回全新数组
  return getArray().slice(1);
}

可选方案:解构语法适配规则

如果你偏好使用解构写法,只要把未使用的变量名替换为eslint规则默认允许忽略的命名(通常为单下划线_)即可规避报错:

function getAnother(): number[] {
  const [_, ...rest] = getArray();
  return rest;
}

如果团队的eslint规则对_也做了校验,增加单行忽略注释即可:

function getAnother(): number[] {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [first, ...rest] = getArray();
  return rest;
}

内容的提问来源于stack exchange,提问作者Heyyy Marco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 11:36:00