reactjs 在Thunk Middleware中输入额外参数时,Redux Toolkit typescript 错误

w41d8nur  于 2023-11-18  发布在  React
关注(0)|答案(1)|浏览(82)

我正在尝试自定义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知道类型吗?
参考文件:

mw3dktmi

mw3dktmi1#

您可以显式键入createAsyncThunk函数。有关详细信息,请参阅Typescript的用法:ASyncThunk。

interface StudentParams {
  query?: string;
  page?: number;
  limit?: number;
}

export const fetchStudents = createAsyncThunk<
  // Return type
  { results: Student[], page: number, query: string },
  // Argument
  StudentParams,
  // ThunkApi
  {
    extra: () => StudentRepository
  }
>(
  'student/fetch',
  async (
    params: StudentParams,
    { fulfillWithValue, rejectWithValue, extra }
  ) => {
    const { query = '', page = 1, limit = 10 } = params;

    try {
      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");
    }
  }
);

字符串
或者你可以强制转换extra类型。我相信下面的方法应该可以。

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 {
      const studentRepository = (extra as () => StudentRepository)();
      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");
    }
  }
);

相关问题