Redux+TypeScript报错:Property 'xxx'不存在于类型'string[]'求助
解决Redux + TypeScript中"Property 'xxx' does not exist on type 'string[]'"类型错误
看起来你遇到的核心问题是TypeScript类型定义和实际API返回结构不匹配,导致了一系列类型冲突。咱们一步步拆解解决:
1. 明确API的实际返回结构
Themealdb的search.php?s=接口返回的数据结构并非直接的字符串数组,而是包含meals字段的对象(搜索不到结果时meals会是null),简化结构如下:
// 定义API响应的类型 interface MealApiResponse { meals: Meal[] | null; } // 定义单条餐食数据的类型,根据你需要的字段补充 interface Meal { idMeal: string; strMeal: string; strMealThumb: string; // 其他字段比如strCategory、strInstructions等按需添加 }
你之前错误地将axios请求的泛型设为string[],这直接导致了后续类型不兼容的问题。
2. 修正State的类型定义
原来的MealState中meal字段定义为string[]是错误的,需要改成实际的餐食对象数组(或允许null,根据你的空状态处理逻辑调整):
export interface Meal { idMeal: string; strMeal: string; strMealThumb: string; // 补充你需要的其他字段 } export interface MealState { meal: Meal[]; // 或 Meal[] | null,根据业务需求选择 input: string; favorites: string[]; // 如果存的是餐食ID,这个类型没问题;存对象的话要改成Meal[] categories: string[]; } // 同步修正initialState const initialState: MealState = { meal: [], input: '', favorites: [], categories: [], };
3. 修正createAsyncThunk的类型与返回值
现在将axios请求的泛型改为正确的MealApiResponse,同时处理meals为null的情况(避免后续state类型冲突):
export const getMeal = createAsyncThunk( 'meal/getMeal', async (search: string) => { const response = await axios.get<MealApiResponse>(`https://www.themealdb.com/api/json/v1/1/search.php?s=${search}`); // 若搜索不到结果,返回空数组而非null,保证类型统一 return response.data.meals || []; } );
4. 调整extraReducers的赋值逻辑
此时action.payload的类型是Meal[],和state中meal的类型完全匹配,直接赋值即可:
extraReducers: (builder) => { builder.addCase(getMeal.fulfilled, (state, action) => { state.meal = action.payload; }); }
5. 修正组件中获取state的方式
现在state.meal.meal已经是餐食对象数组了,不需要再访问.meals属性:
// 错误写法: // const list = useAppSelector((state: RootState) => state.meal.meal.meals) // 正确写法: const list = useAppSelector((state: RootState) => state.meal.meal)
额外注意点
- 如果你之前的
addFavorites动作是用来存储餐食ID的,那favorites: string[]是合理的;如果是存储整个餐食对象,需要将其类型改为Meal[]。 - 记得补充完整
Meal接口的字段,确保和API返回的字段一一对应,这样TypeScript才能提供准确的类型校验。
这样修改后,所有类型错误应该就都解决了,核心就是让TypeScript的类型定义和实际的数据结构完全对应上~
内容的提问来源于stack exchange,提问作者Yohav Rn
相关产品推荐
相关产品推荐

