scopsy / await-to-js

Async await wrapper for easy error handling without try-catch
http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/
MIT License
3.27k stars 153 forks source link

Wrong typings on successful response #14

Closed rdsedmundo closed 5 years ago

rdsedmundo commented 6 years ago

Hello.

I noticed that you're declaring the value of the Promise in case of success as allowed to be undefined per default, and this is wrong.

export declare function to<T, U = any>(promise: Promise<T>, errorExt?: object): Promise<[U | null, T | undefined]>;

What I meant is the T | undefined. This | undefined makes it necessary to check if the successful result is defined, when we already know it's. i.e:

    const [
      downloadError,
      object,
    ] = await to(this.s3.getObject({ Bucket: bucket, Key: key }));

    if (downloadError) {
      return this.throwError(`Unable to download ${bucket}/${key} due to: ${downloadError}`);
    }

    const supportedMimeTypes = ['image/png', 'image/jpg'];

    /* It's saying here that 'object' may be undefined. But we know it isn't as there's no error. */
    if (!supportedMimeTypes.includes(object.ContentType)) {
      return this.throwError(`Unsupported image mimetype: ${object.ContentType}`);
    }

Those typings from this repository, that I remember that had a Pull Request here were more correct: https://github.com/phra/await-to-ts/blob/master/index.ts

i.e: if we know that it could be undefined, we should pass it by ourselves, like await to<[Error, string | undefined]> and not having the library assuming it by default itself.

scopsy commented 5 years ago

Totally agree, added those changes and they should be available soon on npm. Thanks!

bezreyhan commented 5 years ago

Firstly, thank you for this package.

Secondly, has this issue been addressed? I just tested the following code and was still getting type errors:

const waiter = (): Promise<boolean> => Promise.resolve(true);

const test = async (): Promise<boolean> => {
  const [err, res] = await to<boolean>(waiter());
  if (err) {
    return false;
  }

  return res;
};

Typescript complains that res may be undefined. But since we have handled the error case we know that res is defined.