Spaces:
Running
Running
File size: 27,835 Bytes
c2b7eb3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 | import type {
AsyncThunk,
SerializedError,
ThunkDispatch,
UnknownAction,
} from '@reduxjs/toolkit'
import {
configureStore,
createAsyncThunk,
createReducer,
createSlice,
unwrapResult,
} from '@reduxjs/toolkit'
import type { TSVersion } from '@phryneas/ts-version'
import type { AxiosError } from 'axios'
import apiRequest from 'axios'
import type { AsyncThunkDispatchConfig } from '@internal/createAsyncThunk'
const defaultDispatch = (() => {}) as ThunkDispatch<{}, any, UnknownAction>
const unknownAction = { type: 'foo' } as UnknownAction
describe('type tests', () => {
test('basic usage', async () => {
const asyncThunk = createAsyncThunk('test', (id: number) =>
Promise.resolve(id * 2),
)
const reducer = createReducer({}, (builder) =>
builder
.addCase(asyncThunk.pending, (_, action) => {
expectTypeOf(action).toEqualTypeOf<
ReturnType<(typeof asyncThunk)['pending']>
>()
})
.addCase(asyncThunk.fulfilled, (_, action) => {
expectTypeOf(action).toEqualTypeOf<
ReturnType<(typeof asyncThunk)['fulfilled']>
>()
expectTypeOf(action.payload).toBeNumber()
})
.addCase(asyncThunk.rejected, (_, action) => {
expectTypeOf(action).toEqualTypeOf<
ReturnType<(typeof asyncThunk)['rejected']>
>()
expectTypeOf(action.error).toMatchTypeOf<Partial<Error> | undefined>()
}),
)
const promise = defaultDispatch(asyncThunk(3))
expectTypeOf(promise.requestId).toBeString()
expectTypeOf(promise.arg).toBeNumber()
expectTypeOf(promise.abort).toEqualTypeOf<(reason?: string) => void>()
const result = await promise
if (asyncThunk.fulfilled.match(result)) {
expectTypeOf(result).toEqualTypeOf<
ReturnType<(typeof asyncThunk)['fulfilled']>
>()
} else {
expectTypeOf(result).toEqualTypeOf<
ReturnType<(typeof asyncThunk)['rejected']>
>()
}
promise
.then(unwrapResult)
.then((result) => {
expectTypeOf(result).toBeNumber()
expectTypeOf(result).not.toMatchTypeOf<Error>()
})
.catch((error) => {
// catch is always any-typed, nothing we can do here
expectTypeOf(error).toBeAny()
})
})
test('More complex usage of thunk args', () => {
interface BookModel {
id: string
title: string
}
type BooksState = BookModel[]
const fakeBooks: BookModel[] = [
{ id: 'b', title: 'Second' },
{ id: 'a', title: 'First' },
]
const correctDispatch = (() => {}) as ThunkDispatch<
BookModel[],
{ userAPI: Function },
UnknownAction
>
// Verify that the the first type args to createAsyncThunk line up right
const fetchBooksTAC = createAsyncThunk<
BookModel[],
number,
{
state: BooksState
extra: { userAPI: Function }
}
>(
'books/fetch',
async (arg, { getState, dispatch, extra, requestId, signal }) => {
const state = getState()
expectTypeOf(arg).toBeNumber()
expectTypeOf(state).toEqualTypeOf<BookModel[]>()
expectTypeOf(extra).toEqualTypeOf<{ userAPI: Function }>()
return fakeBooks
},
)
correctDispatch(fetchBooksTAC(1))
// @ts-expect-error
defaultDispatch(fetchBooksTAC(1))
})
test('returning a rejected action from the promise creator is possible', async () => {
type ReturnValue = { data: 'success' }
type RejectValue = { data: 'error' }
const fetchBooksTAC = createAsyncThunk<
ReturnValue,
number,
{
rejectValue: RejectValue
}
>('books/fetch', async (arg, { rejectWithValue }) => {
return rejectWithValue({ data: 'error' })
})
const returned = await defaultDispatch(fetchBooksTAC(1))
if (fetchBooksTAC.rejected.match(returned)) {
expectTypeOf(returned.payload).toEqualTypeOf<undefined | RejectValue>()
expectTypeOf(returned.payload).toBeNullable()
} else {
expectTypeOf(returned.payload).toEqualTypeOf<ReturnValue>()
}
expectTypeOf(unwrapResult(returned)).toEqualTypeOf<ReturnValue>()
expectTypeOf(unwrapResult(returned)).not.toMatchTypeOf<RejectValue>()
})
test('regression #1156: union return values fall back to allowing only single member', () => {
const fn = createAsyncThunk('session/isAdmin', async () => {
const response: boolean = false
return response
})
})
test('Should handle reject with value within a try catch block. Note: this is a sample code taken from #1605', () => {
type ResultType = {
text: string
}
const demoPromise = async (): Promise<ResultType> =>
new Promise((resolve, _) => resolve({ text: '' }))
const thunk = createAsyncThunk('thunk', async (args, thunkAPI) => {
try {
const result = await demoPromise()
return result
} catch (error) {
return thunkAPI.rejectWithValue(error)
}
})
createReducer({}, (builder) =>
builder.addCase(thunk.fulfilled, (s, action) => {
expectTypeOf(action.payload).toEqualTypeOf<ResultType>()
}),
)
})
test('reject with value', () => {
interface Item {
name: string
}
interface ErrorFromServer {
error: string
}
interface CallsResponse {
data: Item[]
}
const fetchLiveCallsError = createAsyncThunk<
Item[],
string,
{
rejectValue: ErrorFromServer
}
>('calls/fetchLiveCalls', async (organizationId, { rejectWithValue }) => {
try {
const result = await apiRequest.get<CallsResponse>(
`organizations/${organizationId}/calls/live/iwill404`,
)
return result.data.data
} catch (err) {
const error: AxiosError<ErrorFromServer> = err as any // cast for access to AxiosError properties
if (!error.response) {
// let it be handled as any other unknown error
throw err
}
return rejectWithValue(error.response && error.response.data)
}
})
defaultDispatch(fetchLiveCallsError('asd')).then((result) => {
if (fetchLiveCallsError.fulfilled.match(result)) {
//success
expectTypeOf(result).toEqualTypeOf<
ReturnType<(typeof fetchLiveCallsError)['fulfilled']>
>()
expectTypeOf(result.payload).toEqualTypeOf<Item[]>()
} else {
expectTypeOf(result).toEqualTypeOf<
ReturnType<(typeof fetchLiveCallsError)['rejected']>
>()
if (result.payload) {
// rejected with value
expectTypeOf(result.payload).toEqualTypeOf<ErrorFromServer>()
} else {
// rejected by throw
expectTypeOf(result.payload).toBeUndefined()
expectTypeOf(result.error).toEqualTypeOf<SerializedError>()
expectTypeOf(result.error).not.toBeAny()
}
}
defaultDispatch(fetchLiveCallsError('asd'))
.then((result) => {
expectTypeOf(result.payload).toEqualTypeOf<
Item[] | ErrorFromServer | undefined
>()
return result
})
.then(unwrapResult)
.then((unwrapped) => {
expectTypeOf(unwrapped).toEqualTypeOf<Item[]>()
expectTypeOf(unwrapResult).parameter(0).not.toMatchTypeOf(unwrapped)
})
})
})
describe('payloadCreator first argument type has impact on asyncThunk argument', () => {
test('asyncThunk has no argument', () => {
const asyncThunk = createAsyncThunk('test', () => 0)
expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
[undefined?, AsyncThunkDispatchConfig?]
>()
expectTypeOf(asyncThunk).returns.toBeFunction()
})
test('one argument, specified as undefined: asyncThunk has no argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: undefined) => 0)
expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
[undefined?, AsyncThunkDispatchConfig?]
>()
})
test('one argument, specified as void: asyncThunk has no argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: void) => 0)
expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
})
test('one argument, specified as optional number: asyncThunk has optional number argument', () => {
// this test will fail with strictNullChecks: false, that is to be expected
// in that case, we have to forbid this behavior or it will make arguments optional everywhere
const asyncThunk = createAsyncThunk('test', (arg?: number) => 0)
// Per https://github.com/reduxjs/redux-toolkit/issues/3758#issuecomment-1742152774 , this is a bug in
// TS 5.1 and 5.2, that is fixed in 5.3. Conditionally run the TS assertion here.
type IsTS51Or52 = TSVersion.Major extends 5
? TSVersion.Minor extends 1 | 2
? true
: false
: false
type expectedType = IsTS51Or52 extends true
? (arg: number) => any
: (arg?: number) => any
expectTypeOf(asyncThunk).toMatchTypeOf<expectedType>()
// We _should_ be able to call this with no arguments, but we run into that error in 5.1 and 5.2.
// Disabling this for now.
// asyncThunk()
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[string]>()
})
test('one argument, specified as number|undefined: asyncThunk has optional number argument', () => {
// this test will fail with strictNullChecks: false, that is to be expected
// in that case, we have to forbid this behavior or it will make arguments optional everywhere
const asyncThunk = createAsyncThunk(
'test',
(arg: number | undefined) => 0,
)
expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
expectTypeOf(asyncThunk).toBeCallableWith()
expectTypeOf(asyncThunk).toBeCallableWith(undefined)
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[string]>()
})
test('one argument, specified as number|void: asyncThunk has optional number argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: number | void) => 0)
expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
expectTypeOf(asyncThunk).toBeCallableWith()
expectTypeOf(asyncThunk).toBeCallableWith(undefined)
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[string]>()
})
test('one argument, specified as any: asyncThunk has required any argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: any) => 0)
expectTypeOf(asyncThunk).parameter(0).toBeAny()
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
})
test('one argument, specified as unknown: asyncThunk has required unknown argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: unknown) => 0)
expectTypeOf(asyncThunk).parameter(0).toBeUnknown()
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
})
test('one argument, specified as number: asyncThunk has required number argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: number) => 0)
expectTypeOf(asyncThunk).toMatchTypeOf<(arg: number) => any>()
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
})
test('two arguments, first specified as undefined: asyncThunk has no argument', () => {
const asyncThunk = createAsyncThunk(
'test',
(arg: undefined, thunkApi) => 0,
)
expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
expectTypeOf(asyncThunk).toBeCallableWith()
expectTypeOf(asyncThunk).toBeCallableWith(undefined)
// cannot be called with an argument
expectTypeOf(asyncThunk).parameter(0).not.toBeAny()
expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
[undefined?, AsyncThunkDispatchConfig?]
>()
})
test('two arguments, first specified as void: asyncThunk has no argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: void, thunkApi) => 0)
expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
expectTypeOf(asyncThunk).toBeCallableWith()
expectTypeOf(asyncThunk).parameter(0).toBeVoid()
// cannot be called with an argument
expectTypeOf(asyncThunk).parameter(0).not.toBeAny()
expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
[undefined?, AsyncThunkDispatchConfig?]
>()
})
test('two arguments, first specified as number|undefined: asyncThunk has optional number argument', () => {
// this test will fail with strictNullChecks: false, that is to be expected
// in that case, we have to forbid this behavior or it will make arguments optional everywhere
const asyncThunk = createAsyncThunk(
'test',
(arg: number | undefined, thunkApi) => 0,
)
expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
expectTypeOf(asyncThunk).toBeCallableWith()
expectTypeOf(asyncThunk).toBeCallableWith(undefined)
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameter(0).not.toBeString()
})
test('two arguments, first specified as number|void: asyncThunk has optional number argument', () => {
const asyncThunk = createAsyncThunk(
'test',
(arg: number | void, thunkApi) => 0,
)
expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
expectTypeOf(asyncThunk).toBeCallableWith()
expectTypeOf(asyncThunk).toBeCallableWith(undefined)
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameter(0).not.toBeString()
})
test('two arguments, first specified as any: asyncThunk has required any argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: any, thunkApi) => 0)
expectTypeOf(asyncThunk).parameter(0).toBeAny()
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
})
test('two arguments, first specified as unknown: asyncThunk has required unknown argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: unknown, thunkApi) => 0)
expectTypeOf(asyncThunk).parameter(0).toBeUnknown()
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
})
test('two arguments, first specified as number: asyncThunk has required number argument', () => {
const asyncThunk = createAsyncThunk('test', (arg: number, thunkApi) => 0)
expectTypeOf(asyncThunk).toMatchTypeOf<(arg: number) => any>()
expectTypeOf(asyncThunk).parameter(0).toBeNumber()
expectTypeOf(asyncThunk).toBeCallableWith(5)
expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
})
})
test('createAsyncThunk without generics', () => {
const thunk = createAsyncThunk('test', () => {
return 'ret' as const
})
expectTypeOf(thunk).toEqualTypeOf<AsyncThunk<'ret', void, {}>>()
})
test('createAsyncThunk without generics, accessing `api` does not break return type', () => {
const thunk = createAsyncThunk('test', (_: void, api) => {
return 'ret' as const
})
expectTypeOf(thunk).toEqualTypeOf<AsyncThunk<'ret', void, {}>>()
})
test('createAsyncThunk rejectWithValue without generics: Expect correct return type', () => {
const asyncThunk = createAsyncThunk(
'test',
(_: void, { rejectWithValue }) => {
try {
return Promise.resolve(true)
} catch (e) {
return rejectWithValue(e)
}
},
)
defaultDispatch(asyncThunk())
.then((result) => {
if (asyncThunk.fulfilled.match(result)) {
expectTypeOf(result).toEqualTypeOf<
ReturnType<(typeof asyncThunk)['fulfilled']>
>()
expectTypeOf(result.payload).toBeBoolean()
expectTypeOf(result).not.toHaveProperty('error')
} else {
expectTypeOf(result).toEqualTypeOf<
ReturnType<(typeof asyncThunk)['rejected']>
>()
expectTypeOf(result.error).toEqualTypeOf<SerializedError>()
expectTypeOf(result.payload).toBeUnknown()
}
return result
})
.then(unwrapResult)
.then((unwrapped) => {
expectTypeOf(unwrapped).toBeBoolean()
})
})
test('createAsyncThunk with generics', () => {
type Funky = { somethingElse: 'Funky!' }
function funkySerializeError(err: any): Funky {
return { somethingElse: 'Funky!' }
}
// has to stay on one line or type tests fail in older TS versions
// prettier-ignore
// @ts-expect-error
const shouldFail = createAsyncThunk('without generics', () => {}, { serializeError: funkySerializeError })
const shouldWork = createAsyncThunk<
any,
void,
{ serializedErrorType: Funky }
>('with generics', () => {}, {
serializeError: funkySerializeError,
})
if (shouldWork.rejected.match(unknownAction)) {
expectTypeOf(unknownAction.error).toEqualTypeOf<Funky>()
}
})
test('`idGenerator` option takes no arguments, and returns a string', () => {
const returnsNumWithArgs = (foo: any) => 100
// has to stay on one line or type tests fail in older TS versions
// prettier-ignore
// @ts-expect-error
const shouldFailNumWithArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsNumWithArgs })
const returnsNumWithoutArgs = () => 100
// prettier-ignore
// @ts-expect-error
const shouldFailNumWithoutArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsNumWithoutArgs })
const returnsStrWithNumberArg = (foo: number) => 'foo'
// prettier-ignore
// @ts-expect-error
const shouldFailWrongArgs = createAsyncThunk('foo', (arg: string) => {}, { idGenerator: returnsStrWithNumberArg })
const returnsStrWithStringArg = (foo: string) => 'foo'
const shoulducceedCorrectArgs = createAsyncThunk(
'foo',
(arg: string) => {},
{
idGenerator: returnsStrWithStringArg,
},
)
const returnsStrWithoutArgs = () => 'foo'
const shouldSucceed = createAsyncThunk('foo', () => {}, {
idGenerator: returnsStrWithoutArgs,
})
})
test('fulfillWithValue should infer return value', () => {
// https://github.com/reduxjs/redux-toolkit/issues/2886
const initialState = {
loading: false,
obj: { magic: '' },
}
const getObj = createAsyncThunk(
'slice/getObj',
async (_: any, { fulfillWithValue, rejectWithValue }) => {
try {
return fulfillWithValue({ magic: 'object' })
} catch (rejected: any) {
return rejectWithValue(rejected?.response?.error || rejected)
}
},
)
createSlice({
name: 'slice',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(getObj.fulfilled, (state, action) => {
expectTypeOf(action.payload).toEqualTypeOf<{ magic: string }>()
})
},
})
})
test('meta return values', () => {
// return values
createAsyncThunk<'ret', void, {}>('test', (_, api) => 'ret' as const)
createAsyncThunk<'ret', void, {}>('test', async (_, api) => 'ret' as const)
createAsyncThunk<'ret', void, { fulfilledMeta: string }>('test', (_, api) =>
api.fulfillWithValue('ret' as const, ''),
)
createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
'test',
async (_, api) => api.fulfillWithValue('ret' as const, ''),
)
createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
'test',
// @ts-expect-error has to be a fulfilledWithValue call
(_, api) => 'ret' as const,
)
createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
'test',
// @ts-expect-error has to be a fulfilledWithValue call
async (_, api) => 'ret' as const,
)
createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
'test', // @ts-expect-error should only allow returning with 'test'
(_, api) => api.fulfillWithValue(5, ''),
)
createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
'test', // @ts-expect-error should only allow returning with 'test'
async (_, api) => api.fulfillWithValue(5, ''),
)
// reject values
createAsyncThunk<'ret', void, { rejectValue: string }>('test', (_, api) =>
api.rejectWithValue('ret'),
)
createAsyncThunk<'ret', void, { rejectValue: string }>(
'test',
async (_, api) => api.rejectWithValue('ret'),
)
createAsyncThunk<
'ret',
void,
{ rejectValue: string; rejectedMeta: number }
>('test', (_, api) => api.rejectWithValue('ret', 5))
createAsyncThunk<
'ret',
void,
{ rejectValue: string; rejectedMeta: number }
>('test', async (_, api) => api.rejectWithValue('ret', 5))
createAsyncThunk<
'ret',
void,
{ rejectValue: string; rejectedMeta: number }
>('test', (_, api) => api.rejectWithValue('ret', 5))
createAsyncThunk<
'ret',
void,
{ rejectValue: string; rejectedMeta: number }
>(
'test',
// @ts-expect-error wrong rejectedMeta type
(_, api) => api.rejectWithValue('ret', ''),
)
createAsyncThunk<
'ret',
void,
{ rejectValue: string; rejectedMeta: number }
>(
'test',
// @ts-expect-error wrong rejectedMeta type
async (_, api) => api.rejectWithValue('ret', ''),
)
createAsyncThunk<
'ret',
void,
{ rejectValue: string; rejectedMeta: number }
>(
'test',
// @ts-expect-error wrong rejectValue type
(_, api) => api.rejectWithValue(5, ''),
)
createAsyncThunk<
'ret',
void,
{ rejectValue: string; rejectedMeta: number }
>(
'test',
// @ts-expect-error wrong rejectValue type
async (_, api) => api.rejectWithValue(5, ''),
)
})
test('usage with config override generic', () => {
const typedCAT = createAsyncThunk.withTypes<{
state: RootState
dispatch: AppDispatch
rejectValue: string
extra: { s: string; n: number }
}>()
// inferred usage
const thunk = typedCAT('foo', (arg: number, api) => {
// correct getState Type
const test1: number = api.getState().foo.value
// correct dispatch type
const test2: number = api.dispatch((dispatch, getState) => {
expectTypeOf(dispatch).toEqualTypeOf<
ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>
>()
expectTypeOf(getState).toEqualTypeOf<() => { foo: { value: number } }>()
return getState().foo.value
})
// correct extra type
const { s, n } = api.extra
expectTypeOf(s).toBeString()
expectTypeOf(n).toBeNumber()
if (1 < 2)
// @ts-expect-error
return api.rejectWithValue(5)
if (1 < 2) return api.rejectWithValue('test')
return test1 + test2
})
// usage with two generics
const thunk2 = typedCAT<number, string>('foo', (arg, api) => {
expectTypeOf(arg).toBeString()
// correct getState Type
const test1: number = api.getState().foo.value
// correct dispatch type
const test2: number = api.dispatch((dispatch, getState) => {
expectTypeOf(dispatch).toEqualTypeOf<
ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>
>()
expectTypeOf(getState).toEqualTypeOf<() => { foo: { value: number } }>()
return getState().foo.value
})
// correct extra type
const { s, n } = api.extra
expectTypeOf(s).toBeString()
expectTypeOf(n).toBeNumber()
if (1 < 2) expectTypeOf(api.rejectWithValue).toBeCallableWith('test')
expectTypeOf(api.rejectWithValue).parameter(0).not.toBeNumber()
expectTypeOf(api.rejectWithValue).parameters.toEqualTypeOf<[string]>()
return api.rejectWithValue('test')
})
// usage with config override generic
const thunk3 = typedCAT<number, string, { rejectValue: number }>(
'foo',
(arg, api) => {
expectTypeOf(arg).toBeString()
// correct getState Type
const test1: number = api.getState().foo.value
// correct dispatch type
const test2: number = api.dispatch((dispatch, getState) => {
expectTypeOf(dispatch).toEqualTypeOf<
ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>
>()
expectTypeOf(getState).toEqualTypeOf<
() => { foo: { value: number } }
>()
return getState().foo.value
})
// correct extra type
const { s, n } = api.extra
expectTypeOf(s).toBeString()
expectTypeOf(n).toBeNumber()
if (1 < 2) return api.rejectWithValue(5)
if (1 < 2) expectTypeOf(api.rejectWithValue).toBeCallableWith(5)
expectTypeOf(api.rejectWithValue).parameter(0).not.toBeString()
expectTypeOf(api.rejectWithValue).parameters.toEqualTypeOf<[number]>()
return api.rejectWithValue(5)
},
)
const slice = createSlice({
name: 'foo',
initialState: { value: 0 },
reducers: {},
extraReducers(builder) {
builder
.addCase(thunk.fulfilled, (state, action) => {
state.value += action.payload
})
.addCase(thunk.rejected, (state, action) => {
expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()
})
.addCase(thunk2.fulfilled, (state, action) => {
state.value += action.payload
})
.addCase(thunk2.rejected, (state, action) => {
expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()
})
.addCase(thunk3.fulfilled, (state, action) => {
state.value += action.payload
})
.addCase(thunk3.rejected, (state, action) => {
expectTypeOf(action.payload).toEqualTypeOf<number | undefined>()
})
},
})
const store = configureStore({
reducer: {
foo: slice.reducer,
},
})
type RootState = ReturnType<typeof store.getState>
type AppDispatch = typeof store.dispatch
})
test('rejectedMeta', async () => {
const getNewStore = () =>
configureStore({
reducer(actions = [], action) {
return [...actions, action]
},
})
const store = getNewStore()
const fulfilledThunk = createAsyncThunk<
string,
string,
{ rejectedMeta: { extraProp: string } }
>('test', (arg: string, { rejectWithValue }) => {
return rejectWithValue('damn!', { extraProp: 'baz' })
})
const promise = store.dispatch(fulfilledThunk('testArg'))
const ret = await promise
if (ret.meta.requestStatus === 'rejected' && ret.meta.rejectedWithValue) {
expectTypeOf(ret.meta.extraProp).toBeString()
} else {
// could be caused by a `throw`, `abort()` or `condition` - no `rejectedMeta` in that case
expectTypeOf(ret.meta).not.toHaveProperty('extraProp')
}
})
})
|