React+Redux+TS报错:'never'类型无'roleName'属性,如何定义API接口?
解决TypeScript类型错误:Property 'roleName' does not exist on type 'never'
定义Role数据接口
先明确API返回的角色数据结构,创建对应的TypeScript接口,建议放在单独的类型定义文件(比如src/types/role.ts)里,方便全局复用:// src/types/role.ts export interface Role { id: number | string; // 根据API实际返回类型调整 roleName: string; // 其他API返回的字段,比如description等,按需添加 } // 如果下拉框需要key/value格式,可额外定义 export interface RoleOption { key: number | string; value: number | string; label: string; }修正Redux Store中的类型定义
在Redux Toolkit的slice文件里,给角色数组指定类型,避免默认的never类型:// src/features/user/userSlice.ts import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { Role } from '../../types/role'; interface UserState { roles: Role[]; // 这里指定为Role数组,而不是默认的never[] // 其他状态字段... } const initialState: UserState = { roles: [], // 初始值为空数组,类型匹配Role[] // 其他初始状态... }; const userSlice = createSlice({ name: 'user', initialState, reducers: { setRoles: (state, action: PayloadAction<Role[]>) => { state.roles = action.payload; }, // 其他reducer... }, }); export const { setRoles } = userSlice.actions; export default userSlice.reducer;在组件中使用正确的类型
在添加用户侧边栏组件里,从Redux获取roles时,确保类型正确:// src/components/AddUserSidebar.tsx import { useSelector } from 'react-redux'; import { RootState } from '../../store'; // 导入根状态类型 import { Role, RoleOption } from '../../types/role'; const AddUserSidebar = () => { // 获取roles并指定类型(如果RootState定义正确,可省略as Role[]) const roles = useSelector((state: RootState) => state.user.roles); // 转换为下拉框需要的选项格式(如果需要) const roleOptions: RoleOption[] = roles.map(role => ({ key: role.id, value: role.id, label: role.roleName, })); return ( <div className="sidebar"> <select> {roles.map(p => ( <option key={p.id} value={p.id}> {p.roleName} </option> ))} </select> </div> ); }; export default AddUserSidebar;补充根状态类型(如果还没定义)
在Redux的store文件里,定义RootState类型,让useSelector能自动推断类型:// src/store.ts import { configureStore } from '@reduxjs/toolkit'; import userReducer from './features/user/userSlice'; export const store = configureStore({ reducer: { user: userReducer, // 其他reducer... }, }); // 导出根状态类型 export type RootState = ReturnType<typeof store.getState>; export type AppDispatch = typeof store.dispatch;
这样处理后,TypeScript就能正确识别roles数组中每个元素的类型,不会再出现never类型的错误。
内容的提问来源于stack exchange,提问作者Biplab Paul
相关产品推荐
相关产品推荐

