diff --git a/README.md b/README.md index be49a50..687452b 100644 --- a/README.md +++ b/README.md @@ -130,21 +130,19 @@ console.log(data) ``` ```ts -const result = await until(() => action()) +const { data, error } = await until(() => action()) // At this point, "data" is ambiguous "DataType | null" -// which is correct, as you haven't checked nor handled the "error". +// which is correct, as you haven't checked or handled the "error". -if (result.error) { +if (error) { return null } // Data is strict "DataType" since you've handled the "error" above. -console.log(result.data) +console.log(data) ``` -> It's crucial to keep the entire result of the `Promise` in a single variable and not destructure it. TypeScript will always keep the type of `error` and `data` as it was upon destructuring, ignoring any type guards you may perform later on. - ## Special thanks - [giuseppegurgone](https://twitter.com/giuseppegurgone) for the discussion about the original `until` API. diff --git a/package.json b/package.json index a640d60..a85a80a 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "jest": "^26.6.3", "ts-jest": "^26.5.4", "tsup": "^6.2.3", - "typescript": "^4.2.4" + "typescript": "^4.6.4" }, "scripts": { "start": "tsc -w", @@ -34,4 +34,4 @@ "build": "tsup", "release": "release publish" } -} \ No newline at end of file +} diff --git a/src/until.ts b/src/until.ts index 6f31362..039e700 100644 --- a/src/until.ts +++ b/src/until.ts @@ -10,8 +10,11 @@ export type AsyncTuple< /** * Gracefully handles a given Promise factory. + * @template ErrorType The type of the error promise may throw. + * @template DataType The type of the data promise may return. + * @param promise function that returns a promise. * @example - * const { error, data } = await until(() => asyncAction()) + * const { error, data } = await until(() => fetchUser(id)) */ export const until = async < ErrorType extends any = Error, @@ -20,11 +23,11 @@ export const until = async < promise: () => Promise, ): Promise> => { try { - const data = await promise().catch((error) => { + const data = await promise().catch((error: ErrorType) => { throw error }) return { error: null, data } } catch (error) { - return { error, data: null } + return { error: error as ErrorType, data: null } } }