Skip to content

Instantly share code, notes, and snippets.

@destroytoday
Last active December 18, 2020 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save destroytoday/b4c035b2ceeabe67b74f67fc91128c22 to your computer and use it in GitHub Desktop.
Save destroytoday/b4c035b2ceeabe67b74f67fc91128c22 to your computer and use it in GitHub Desktop.
/*
Typescript erroring:
---
Type 'Promise<(T | undefined)[] | [any, undefined]>' is not assignable to type 'Promise<[void | Error, void | T]>'.
Type '(T | undefined)[] | [any, undefined]' is not assignable to type '[void | Error, void | T]'.
Type '(T | undefined)[]' is not assignable to type '[void | Error, void | T]'.
Target requires 2 element(s) but source may have fewer.ts(2322)
*/
export default function <T> (promise: Promise<T>): Promise<[Error | void, T | void]> {
return promise
.then((data) => ([undefined, data]))
.catch((error) => ([error, undefined]))
}
/*
Usage:
const [err, res] = await handle(Axios.get('/api/foo'))
*/
@destroytoday
Copy link
Author

Fixed! Thanks, @dlo! (https://twitter.com/dwlz/status/1340082549369036800)

export default function <T> (promise: Promise<T>): Promise<[Error | void, T | void]> {
  return promise
    .then((data: T) => [undefined, data] as [Error | void, T | void])
    .catch((error: Error) => [error, undefined]);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment