所以我使用以下代码来获取用户列表,
export const fetchUserById = createAsyncThunk(
"users/fetchById",
async (_, { rejectWithValue, fulfillWithValue }) => {
try {
const response = await fetch(`https://reqres.in/api/users`)
const j = (await response.json()) as MyData[]
return fulfillWithValue(j)
} catch (e) {
return rejectWithValue(e.response)
}
}
)
打字稿出现以下错误,
Argument of type '(_: void, { rejectWithValue, fulfillWithValue }: GetThunkAPI<{}>) => Promise<RejectWithValue<unknown, unknown> | FulfillWithMeta<MyData[], unknown>>' is not assignable to parameter of type 'AsyncThunkPayloadCreator<MyData[], void, {}>'.
Type 'Promise<RejectWithValue<unknown, unknown> | FulfillWithMeta<MyData[], unknown>>' is not assignable to type 'AsyncThunkPayloadCreatorReturnValue<MyData[], {}>'.
Type 'Promise<RejectWithValue<unknown, unknown> | FulfillWithMeta<MyData[], unknown>>' is not assignable to type 'Promise<RejectWithValue<unknown, unknown> | MyData[]>'.
Type 'RejectWithValue<unknown, unknown> | FulfillWithMeta<MyData[], unknown>' is not assignable to type 'RejectWithValue<unknown, unknown> | MyData[]'.
Type 'FulfillWithMeta<MyData[], unknown>' is not assignable to type 'RejectWithValue<unknown, unknown> | MyData[]'.
Type 'FulfillWithMeta<MyData[], unknown>' is not assignable to type 'RejectWithValue<unknown, unknown>'.
Types have separate declarations of a private property '_type'.ts(2345)
答案 0 :(得分:1)
为 fulfillWithValue
泛型参数的 ThunkApiConfig
属性指定类型。
import { createAsyncThunk } from '@reduxjs/toolkit';
interface MyData {}
export const fetchUserById = createAsyncThunk<MyData[], void, { fulfilledMeta: any }>(
'users/fetchById',
async (_, { rejectWithValue, fulfillWithValue }) => {
try {
const response = await fetch(`https://reqres.in/api/users`);
const j = await response.json();
return fulfillWithValue(j, null);
} catch (e) {
return rejectWithValue(e.response);
}
},
);
软件包版本:"@reduxjs/toolkit": "^1.6.0"