如何从TypeScript联合类型Actions中提取type属性值生成新类型
你可以直接使用 TypeScript 自带的索引访问类型语法实现需求,无需额外工具类型:
type ActionTypes = Actions['type']
此时 ActionTypes 会自动推导为 "addToCart" | "removeFromCart" 的联合类型。
原理解释
因为 Actions 本身是多个接口的联合类型,当使用索引访问联合类型的公共属性时,TypeScript 会自动遍历联合的每一个成员,取出对应属性的类型再合并成新的联合类型,完全符合你的预期。
后续你新增其他 Action 接口扩展 Actions 联合时,ActionTypes 也会自动同步新增的 type 值,不需要手动维护。
完整可运行示例:
// 你可以自行补充Book的属性定义 interface Book { id: string title: string } interface AddToCart { type: "addToCart" book: Book } interface RemoveFromCart { type: "removeFromCart" book: Book } type Actions = AddToCart | RemoveFromCart // 提取type联合类型的核心代码 type ActionTypes = Actions['type']
内容的提问来源于stack exchange,提问作者arminfro
相关产品推荐
相关产品推荐

