能否在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
相关产品推荐
相关产品推荐

