TypeScript类静态异步方法重载触发ESLint重复成员错误如何解决?
解决TypeScript类方法重载导致的ESLint「Duplicate name 'login'」错误
我尝试对AuthAPI类的静态异步login方法进行重载,要求传入LoginData参数时返回类型推断为LoginResponse,无参数时返回类型为void | Error,类采用单例模式。但在VSCode中触发了「Duplicate name 'login' eslint no-dupe-class-members」错误,Replit中无此问题,推测是ESLint配置问题。
相关代码
AuthAPI类
export default class AuthAPI { private static instance: AuthAPI; private serverToken: string; private constructor(serverToken: string) { this.serverToken = serverToken; } static async login(loginData: LoginData): Promise<LoginResponse>; static async login(): Promise<Error | void>; static async login( loginData?: LoginData, ): Promise<LoginResponse | Error | void> { if (loginData === undefined) { if (Math.random() * 1000 === 401) { return new Error("Token expired; Couldn't log in locally"); } if (Math.random() * 1000 === 200) { return; } } if (loginData) { return {token: 'a string', user: 'user'}; } } }
类型定义
export interface LoginData { loginEmail?: string; username?: string; password: string; } export type LoginResponse = { token: string; user: string; };
原ESLint配置
module.exports = { root: true, extends: '@react-native-community', parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], overrides: [ { files: ['*.ts', '*.tsx'], rules: { '@typescript-eslint/no-shadow': ['error'], 'no-shadow': 'off', 'no-undef': 'off', 'react-native/no-inline-styles': 0, 'prettier/prettier': [ 'error', { 'no-inline-styles': false, }, ], 'react/self-closing-comp': 'off', 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': 'off', 'react-hooks/rules-of-hooks': 'off', 'react-hooks/exhaustive-deps': 'off', }, }, ], };
解决方案
问题根源是原生ESLint的no-dupe-class-members规则不识别TypeScript的方法重载语法,需要禁用原生规则,启用@typescript-eslint提供的对应规则——它能正确处理TS重载逻辑。
修改ESLint配置中的TypeScript文件规则,新增以下两项配置:
- 关闭原生
no-dupe-class-members规则 - 启用
@typescript-eslint/no-dupe-class-members规则
修改后的完整配置:
module.exports = { root: true, extends: '@react-native-community', parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], overrides: [ { files: ['*.ts', '*.tsx'], rules: { '@typescript-eslint/no-shadow': ['error'], 'no-shadow': 'off', 'no-undef': 'off', // 适配TS方法重载的核心配置 'no-dupe-class-members': 'off', '@typescript-eslint/no-dupe-class-members': ['error'], 'react-native/no-inline-styles': 0, 'prettier/prettier': [ 'error', { 'no-inline-styles': false, }, ], 'react/self-closing-comp': 'off', 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': 'off', 'react-hooks/rules-of-hooks': 'off', 'react-hooks/exhaustive-deps': 'off', }, }, ], };
@typescript-eslint/no-dupe-class-members是专门为TypeScript设计的规则,它会忽略合法的方法重载,仅在出现真正重复的类成员(比如两个同名且参数签名完全一致的方法)时才触发报错,完美适配你的重载场景。
内容的提问来源于stack exchange,提问作者Hack3r
相关产品推荐
相关产品推荐

