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

如何修复ESLint误报已使用的TypeScript Props接口未使用错误

问题描述

我有一个组件将AvatarProps作为props类型使用:
组件使用AvatarProps类型的代码截图

对应接口声明代码如下:

export interface AvatarProps {
  userName: string;
  userLastName: string;
  userImg?: string;
  onPress?: Function;
  backgroundColorAvatar?: string;
  editMode?: boolean;
  onPressEdit?: Function;
  editButtonIcon?: string;
  backgroundColorEditButton?: string;
  textStyle?: TextStyle;
}

运行ESLint时抛出如下报错:

5:15  error    'AvatarProps' is defined but never used  

项目通过lefthook配置了代码提交时自动触发ESLint校验,lefthook.yml配置内容如下:

pre-commit:
  parallel: true
  commands:
    lint:
      files: git diff --name-only @{push}
      glob: "*.{js,ts,jsx,tsx}"
      run: npx eslint {files}
    types:
      files: git diff --name-only @{push}
      glob: "*.{js,ts, jsx, tsx}"
      run: npx tsc --noEmit
commit-msg:
  parallel: true
  commands:
    commitlint:
      run: npx commitlint --edit

求规范的报错消除方案。

解决方案

这个报错是ESLint规则适配和hook配置问题共同导致的,按以下优先级处理即可,不要直接加eslint忽略注释凑数:

  • 先修ESLint规则:原生的no-unused-vars规则不识别TypeScript的interface、type语法,会把导出的类型误判为未使用。把配置里的原生规则关闭,替换为TS版本的规则即可:
// .eslintrc.js / .eslintrc 配置片段
rules: {
  // 关闭原生不兼容TS的规则
  "no-unused-vars": "off",
  // 开启TS专属的未使用变量检查规则
  "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }]
}
  • 再修正lefthook的文件扫描逻辑:你现在pre-commit钩子取文件用的@{push}是pre-push阶段的参数,pre-commit阶段应该扫描暂存区文件,否则如果本次提交只改了声明AvatarProps的文件、没改引用该类型的组件文件,ESLint单独扫描声明文件时自然会判定类型未被使用。把对应配置改成如下即可:
pre-commit:
  parallel: true
  commands:
    lint:
      files: git diff --name-only --cached
      glob: "*.{js,ts,jsx,tsx}"
      run: npx eslint {files}
    types:
      files: git diff --name-only --cached
      glob: "*.{js,ts,jsx,tsx}"
      run: npx tsc --noEmit
  • 最后做基础检查:确认组件文件中AvatarProps的导入路径正确,且确实在组件props类型标注位置使用了该类型,不存在导入后拼错名称、漏写类型标注的低级问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 18:31:28