React TypeScript中如何按路径名分配条件类型接收多API数据
React TypeScript 基于路径名分配条件类型实现单状态管理多类型数据
核心思路
通过定义路径-数据类型映射实现条件类型绑定,去掉冗余的any类型,同时保证后续使用时TS可以自动收窄类型,获得完整的类型提示。
步骤1:定义基础类型关联规则
先统一管理所有页面路径和对应的数据类型,避免硬编码:
// 枚举所有页面路径,避免拼写错误 enum PagePath { 位置列表 = '/bmv_location_list', 全部订单 = '/orders', 新订单 = '/new-orders' } // 定义路径和对应数据类型的映射关系 type PageDataTypeMap = { [PagePath.位置列表]: LocationInterface[] [PagePath.全部订单]: SingleOrder[] [PagePath.新订单]: SingleOrder[] } // 自动推导状态支持的所有数据类型 type TableArrayType = PageDataTypeMap[keyof PageDataTypeMap] | undefined
步骤2:改造useState类型定义
去掉原来的any类型,使用上面推导的联合类型:
const [tableArray, setTableArray] = useState<TableArrayType>()
步骤3:优化赋值逻辑(可选)
可以用对象映射代替多分支if-else,后续新增路径时维护更简单:
useEffect(() => { setLoading(true); const pathDataMap: Record<PagePath, TableArrayType> = { [PagePath.位置列表]: locationList, [PagePath.全部订单]: fetchOrdersListData, [PagePath.新订单]: newOrders } const currentData = pathDataMap[pathname as PagePath] if (currentData) { setTableArray(currentData) } setLoading(false); }, [fetchOrdersListData, locationList, newOrders, pathname]);
步骤4:使用时自动收窄类型
后续操作tableArray时,只需要判断当前路径,TS就会自动匹配对应的数据类型,无需额外类型断言:
if (pathname === PagePath.位置列表) { // 此处tableArray自动识别为 LocationInterface[] | undefined tableArray?.forEach(item => { // 可以直接调用LocationInterface的属性,获得完整类型提示 console.log(item.address, item.id) }) } else if (pathname === PagePath.全部订单 || pathname === PagePath.新订单) { // 此处tableArray自动识别为 SingleOrder[] | undefined tableArray?.forEach(item => { console.log(item.orderNo, item.amount) }) }
注意事项
- 所有路径统一通过枚举管理,不要直接写字符串字面量,避免拼写错误导致类型不匹配
- 新增页面时只需要在
PagePath和PageDataTypeMap中新增对应配置即可,无需修改其他逻辑 - 不要额外加
any类型,否则会丢失所有类型校验能力
内容的提问来源于stack exchange,提问作者Asad
相关产品推荐
相关产品推荐

