You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript多个同类型变量如何统一声明?React Props接口简写方法

解决方案

你可以使用TypeScript的映射类型+模板字面量联合类型,一行完成所有同规则同类型字段的定义,和你原有interface的效果完全等价:

type IcarouselProps = { [Key in `img${1|2|3|4|5|6}` | `heading${1|2|3|4|5|6}`]: string }

如果你的字段命名没有统一的前缀+数字规则,也可以用Record工具类型联合所有字段名实现一行定义:

type IcarouselProps = Record<'img1'|'img2'|'img3'|'img4'|'img5'|'img6'|'heading1'|'heading2'|'heading3'|'heading4'|'heading5'|'heading6', string>

如果Props还需要追加其他不同类型的字段,可以用交叉类型合并定义:

// 示例:额外添加自动播放、轮播间隔两个不同类型的字段
type IcarouselProps = { [Key in `img${1|2|3|4|5|6}` | `heading${1|2|3|4|5|6}`]: string } & {
  autoplay: boolean
  duration: number
}

内容的提问来源于stack exchange,提问作者Mohammad Noushad Siddiqui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:06:08