Skip to content

Commit

Permalink
add throwErrorsFromPromise helper
Browse files Browse the repository at this point in the history
  • Loading branch information
phryneas committed Feb 15, 2020
1 parent 5f7afe9 commit 3a52668
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
7 changes: 7 additions & 0 deletions etc/redux-toolkit.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,13 @@ export function createAsyncThunk<ActionType extends string, Returned, ActionPara
args: ActionParams;
requestId: string;
}>;
throwErrorsFromPromise: (returned: import("./createAction").PayloadAction<Returned, string, {
args: ActionParams;
requestId: string;
}, never> | import("./createAction").PayloadAction<undefined, string, {
args: ActionParams;
requestId: string;
}, Error>) => Returned;
};

// @alpha (undocumented)
Expand Down
18 changes: 17 additions & 1 deletion src/createAsyncThunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Dispatch } from 'redux'
import nanoid from 'nanoid'
import { createAction } from './createAction'

type Await<P> = P extends PromiseLike<infer T> ? T : P

type AsyncThunksArgs<S, E, D extends Dispatch = Dispatch> = {
dispatch: D
getState: S
Expand Down Expand Up @@ -129,5 +131,19 @@ export function createAsyncThunk<
}
}

return Object.assign(actionCreator, { pending, rejected, fulfilled })
function throwErrorsFromPromise(
returned: Await<ReturnType<ReturnType<typeof actionCreator>>>
) {
if (rejected.match(returned)) {
throw returned.error
}
return returned.payload
}

return Object.assign(actionCreator, {
pending,
rejected,
fulfilled,
throwErrorsFromPromise
})
}
15 changes: 14 additions & 1 deletion type-tests/files/createAsyncThunk.typetest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createAsyncThunk, Dispatch, createReducer, AnyAction } from 'src'
import { ThunkDispatch } from 'redux-thunk'
import { promises } from 'fs'

function expectType<T>(t: T) {
return t
Expand Down Expand Up @@ -29,7 +30,8 @@ function fn() {}
})
)

const result = await dispatch(async(3))
const promise = dispatch(async(3))
const result = await promise

if (async.fulfilled.match(result)) {
expectType<ReturnType<typeof async['fulfilled']>>(result)
Expand All @@ -40,4 +42,15 @@ function fn() {}
// typings:expect-error
expectType<ReturnType<typeof async['fulfilled']>>(result)
}

promise
.then(async.throwErrorsFromPromise)
.then(result => {
expectType<number>(result)
// typings:expect-error
expectType<Error>(result)
})
.catch(error => {
// catch is always any-typed, nothing we can do here
})
})()

0 comments on commit 3a52668

Please sign in to comment.