Typescript 函数重载遇到 Eslint 报错

203 阅读1分钟

问题描述

// helper/type.ts
function toValues(data: OriginData.Brief): OriginValues.Brief
function toValues(data: OriginData.Detail): OriginValues.Detail
function toValues(data: OriginData.Detail): OriginValues.Update {
  const { sourceImg, ...rest } = data

  return {
    image: {
      src: data.sourceImg.resourceUrl,
      width: data.sourceImg.width || 0,
      height: data.sourceImg.height || 0,
    },
    ...rest,
  }
}

当我们定义函数重载时报错如下:

'toValues' is already defined. eslint(no-redeclare)

image.png

排查

问题的原因在于 javescript 是不支持函数重载的,上述的写法会让eslint误认为我们重复定义了 toValues 这个函数,因此报错 no-redeclare

而在 typescript 中,函数重载仅作为一种静态类型的校验工具是可以存在的。详见:Function Overloads

解决

参考 no-redeclare,它提供了一种绕开这种误报的方法:

//.eslintrc.cjs
module.exports = {
  "rules": {
    // 避免 `eslint` 对于 `typescript` 函数重载的误报
    "no-redeclare": "off",
    "@typescript-eslint/no-redeclare": "error"
  }

其用意在于关闭 eslint/no-redeclare 并使用 @typescript-eslint/no-redeclare 代替之。