【问题标题】:ESLint: Unexpected any. Specify a different type.(@typescript-eslint/no-explicit-any)ESLint:出乎意料。指定不同的类型。(@typescript-eslint/no-explicit-any)
【发布时间】:2021-11-09 05:34:45
【问题描述】:

我有这行代码,它是一个包装函数,即使它工作正常, const to = (promise: any) => promise.then((data: any) => data).catch((err: any) => err);

但是如果我不包含 eslint-disable-next-line,eslint 会提示意外的任何错误

ESLint: Unexpected any. Specify a different type.(@typescript-eslint/no-explicit-any)

函数包装器to()可用于包装不同的登录方法,例如此函数,

const loginWithEmail = async (email:string, password:string) => new Promise((reject) => {
  const firebase = getFirebase();
  firebase.login({
    email,
    password,
  }).catch((error) => {
    reject(error);
    return error.message;
  });
});

最终结果被放置在一个 React 组件中,在那里它将获取错误消息并将其放入要显示的钩子中。

  const handleEmailLogin = async () => {
    const err = await to(loginWithEmail(email, password));
    setEmailLoginError(err.message);
  };

我想知道是否有更好的方法来定义函数 to() 而不依赖于类型 any?

【问题讨论】:

    标签: reactjs typescript function firebase-authentication react-hooks


    【解决方案1】:

    .then 完全是多余的,因为它返回了 Promise 解析的值 - 只需使用原始 Promise。

    .catch 将拒绝的值转换为已解析的值,而无需对其进行任何其他操作。这对 IMO 来说是非常奇怪的——你真的想忽略错误吗? - 但如果你确实想这样做,那么只需完全省略 err 的类型参数(它会被键入为 unknown)。

    promise 应输入为 Promise<unknown> 以表明它是一个可以解析为任何值的 Promise。

    const to = (promise: Promise<unknown>) => promise.catch(err => err);
    

    但完全删除to 函数可能更有意义。

    您的loginWithEmail 函数看起来也有些损坏。 .login 返回一个 Promise,所以不需要 construct another one around it - 并且 .catch 的返回值没有在其他地方使用,所以 return error.message 没有做任何事情。

    只考虑

    const loginWithEmail = (email:string, password:string) =>
      getFirebase()
        .login({
            email,
            password,
        });
    

    【讨论】:

    • 是的,我同意这一点,但我需要返回错误消息。不过好点,我不知道为什么要写 to() 或者它是一个没有任何意义的实用程序,所以我决定删除它并直接在函数本身上处理错误返回。
    猜你喜欢
    • 2020-02-16
    • 2020-03-11
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2020-03-23
    • 2020-11-27
    • 2020-04-09
    相关资源
    最近更新 更多