TypeScript基于组件Key的动态Props优化:替换any类型方案咨询
重构TypeScript动态组件映射:替换any类型的最优方案
针对你用ComponentKeys枚举实现动态组件映射但依赖any类型的问题,这里提供一套强类型重构方案,能让TypeScript自动校验组件与props的匹配性,彻底消除类型不安全的any:
1. 创建组件Props映射类型
先定义一个映射类型,将每个枚举键与对应的props类型绑定:
type ComponentPropsMap = { [ComponentKeys.TEXT]: TextProps; [ComponentKeys.LIST]: ListProps; [ComponentKeys.MODAL]: ModalProps; };
2. 给组件映射对象添加强类型约束
利用React内置的ComponentType和TypeScript索引类型,确保每个枚举键对应的组件只能接收匹配的props:
import type { ComponentType } from 'react'; const components: { [K in ComponentKeys]: ComponentType<ComponentPropsMap[K]>; } = { [ComponentKeys.TEXT]: TextComponent, [ComponentKeys.LIST]: ListComponent, [ComponentKeys.MODAL]: ModalComponent, };
3. 改造MappedComponent为泛型组件
通过泛型绑定componentKey与componentProps的类型关系,让TypeScript做实时校验:
export const MappedComponent = <K extends ComponentKeys>(props: { componentKey: K; componentProps: ComponentPropsMap[K]; }) => { const Component = components[props.componentKey]; return <Component {...props.componentProps} />; };
效果示例
现在使用组件时,TypeScript会自动校验props的正确性:
// 合法用法,完全符合类型约束 <MappedComponent componentKey={ComponentKeys.TEXT} componentProps={{ label: 'Hello World' }} /> // 非法用法,TypeScript会直接报错(props结构不匹配TEXT组件要求) <MappedComponent componentKey={ComponentKeys.TEXT} componentProps={{ heading: '错误示例' }} />
内容的提问来源于stack exchange,提问作者blahdeblah
相关产品推荐
相关产品推荐

