Typescript 类不允许静态异步方法重载

问题描述 投票:0回答:1

我试图重载登录函数,以便当我向其传递参数时,返回类型被推断为

LoginResponse
,当我不传递任何参数时,它被推断为
void | Error
。我正在使用单例模式,所以这就是为什么我像这样定义顶部的字段 这是我课程的相关部分

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>;
  // login method if there is loginData given
  static async login(
    loginData?: LoginData,
  ): Promise<LoginResponse | Error | void> {
    /** try sending a request with localStorage token
     * and if there's a 401 error the token isn't valid anymore.
     * then try logging in with loginData */

    // try signing in with local token in storage
    if (loginData === undefined) {
      // try sending a request and if there's a 401 error the token isn't valid anymore

      if (Math.random() * 1000 === 401) {
        return new Error("Token expired; Couldn't log in locally");
      }
      if (Math.random() * 1000 === 200) {
        return;
      }
    }
    if (loginData) {
      // if not log in with a request to the server
      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',
      },
    },
  ],
};

我在 vscode 中遇到

Duplicate name 'login' eslint no-dupe-class-members
错误。我如何解决它? enter image description here

我检查了是否有多个实现,但没有。我尝试在replit Playground上重现该问题,并且没有错误。我认为问题出在 eslint 上。

typescript oop overloading eslint typescript-eslint
1个回答
0
投票

我解决了!

问题是我的默认 eslint 配置启用了“no-duplicate-class-members”。我将其关闭,因为不需要它,正如 @jcalz 所说,现在它已修复。

© www.soinside.com 2019 - 2024. All rights reserved.