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

能否在TypeScript中扩展元组类型?无重复定义实现类型继承

TypeScript元组类型扩展实现方法

当然可以,不需要重复Sandwich的代码,利用TypeScript的元组展开操作符就能实现元组类型的"继承"扩展:

首先保留你的原定义:

type Sandwich = [name: string, toppings: object]

然后直接通过展开Sandwich来定义HotDog:

type HotDog = [...Sandwich, length: number]

这个写法会自动将Sandwich的所有元素类型和标签整合到HotDog中,同时在末尾追加新的length: number元素,完全符合你想要的结构。

验证一下类型效果:

const myHotDog: HotDog = ["Classic Dog", { mustard: true }, 20]
// 类型检查正常通过,结构与预期一致

另外这种方式还支持在元组开头添加新元素,比如:

type LabeledHotDog = [category: string, ...Sandwich, length: number]
// 这个类型会是 [category: string, name: string, toppings: object, length: number]

内容的提问来源于stack exchange,提问作者Sasgorilla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:31:41