我正在尝试自定义Redux工具包中包含的中间件来添加一个额外的参数。这个额外的参数是一个仓库的实现。
当我配置存储时,我添加了额外的参数:
export const store = configureStore({
reducer: {
students: students,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
thunk: {
extraArgument: createAPIStudentRepository,
},
serializableCheck: false,
}),
});
字符串createAPIStudentRepository
的类型为StudentRepository
:
export const createAPIStudentRepository = (): StudentRepository => {
return {
loadStudents: async (query: string, page: number, limit: number) => {
const response = await fetch(API_STUDENTS_URL(query, page, limit));
const results = (await response.json()) as Student[];
return results;
},
};
};
型
下面是Student
存储库:
export interface StudentRepository {
loadAStudents(
query: string,
page: number,
limit: number
): Promise<Student[]>;
}
型
然后,在我的Redux Thunk中,我想使用我在配置商店时注入的createAPIStudentRepository
:
interface StudentParams {
query?: string;
page?: number;
limit?: number;
}
export const fetchStudents = createAsyncThunk(
'student/fetch',
async (
params: StudentParams,
{ fulfillWithValue, rejectWithValue, extra }
) => {
const { query = '', page = 1, limit = 10 } = params;
try {
//TODO: here is the problem, extra() throws an error: "extra" is of type
//"unknown"
const studentRepository = extra();
const results = await studentRepository.loadAStudents(
query,
page,
limit
);
return { results, page, query };
} catch (error: unknown) {
console.log(error);
return rejectWithValue("Error: couldn't fetch Students");
}
}
);
型
问题出在TODO
行。这段代码可以工作,但我得到一个Typescript
错误:"extra" is of type "unknwon"
。
有什么办法可以让Typescript
知道类型吗?
参考文件:
1条答案
按热度按时间mw3dktmi1#
您可以显式键入
createAsyncThunk
函数。有关详细信息,请参阅Typescript的用法:ASyncThunk。字符串
或者你可以强制转换
extra
类型。我相信下面的方法应该可以。型