TypeScript 如何实现 CarouselProps 的 slides 类型随 type 属性取值动态切换
TypeScript 轮播组件属性类型联动实现方案
你当前的写法使用交叉类型CardFullProps & CardHalfProps要求slides同时满足两种卡片的属性定义,无法实现根据type值动态匹配slides类型的需求,可通过以下两种方案实现:
方案1:判别联合类型(无泛型,场景简单时优先选用)
通过将CarouselProps定义为两种类型的联合,以type作为判别因子,TS可自动根据type值收窄slides的类型:
export enum CardType { full, half } // 你的卡片属性定义 interface CardFullProps { fullWidthContent: string; // 其他全卡片专属属性 } interface CardHalfProps { halfWidthContent: string; // 其他半卡片专属属性 } export type CarouselProps = | { type: CardType.full; slides: CardFullProps[]; slidesPerView?: number; } | { type: CardType.half; slides: CardHalfProps[]; slidesPerView?: number; };
方案2:泛型+类型映射(可扩展,适合后续新增卡片类型场景)
如果后续会新增更多CardType枚举值,用泛型方案可减少重复代码,仅需维护类型映射即可:
export enum CardType { full, half } interface CardFullProps { fullWidthContent: string; } interface CardHalfProps { halfWidthContent: string; } // 枚举值与卡片属性的映射表,新增卡片类型仅需在此处添加对应关系 type CardTypeMap = { [CardType.full]: CardFullProps; [CardType.half]: CardHalfProps; } // 泛型绑定type与slides的类型关系 export type CarouselProps<T extends CardType = CardType> = { type: T; slides: CardTypeMap[T][]; slidesPerView?: number; };
效果验证
两种方案都可实现类型校验:当type指定为CardType.full时,slides传入CardHalfProps类型数据会直接触发TS类型报错。
内容的提问来源于stack exchange,提问作者they call me wolf
相关产品推荐
相关产品推荐

