0

I have this line of code which is a wrapper function even though it works fine, const to = (promise: any) => promise.then((data: any) => data).catch((err: any) => err);

but eslint is prompting the unexpected any error, if i do not include eslint-disable-next-line

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

the function wrapper to() can be used to wrap different login methods for example this function,

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

and the end result is placed inside a React Component where it will get the err message and place it into a hook to be displayed.

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

i was wondering if there's a better way to define the function to() without relying on the type any?

1 Answers1

0

The .then is completely superfluous, since it returns the value the Promise resolved with - just use the original Promise.

The .catch turns the rejected value into a resolved value, without doing anything else with it. This is exceedingly strange to do IMO - do you really want to ignore errors ? - but if you do want to do this, then simply omit the type parameter entirely for the err (and it'll be typed as unknown).

The promise should be typed as Promise<unknown> to indicate that it's a Promise that could resolve to any value.

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

But it'd probably make more sense to remove the to function entirely.

Your loginWithEmail function looks somewhat broken too. .login returns a Promise, so there's no need to construct another one around it - and the return value of the .catch isn't used elsewhere, so return error.message isn't doing anything.

Consider just

const loginWithEmail = (email:string, password:string) =>
  getFirebase()
    .login({
        email,
        password,
    });
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • yes i would agree with that, but i need the error messages returned. good point though, i got no idea why the `to()` was written either it was a utility which served no meaning, so i decided to remove it and handle the error return directly on the function itself. – melchsee263 Sep 14 '21 at 03:44