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

如何在TypeScript中复用对象类型,消除嵌套数组对象的类型重复?

如何消除TypeScript嵌套对象类型的属性重复定义?

针对你提出的嵌套对象数组类型定义冗余问题,有几种简洁的解决方式:

1. 接口继承

让包含子项的接口继承基础项接口,直接复用共享属性:

// 定义基础子项类型
interface Item {
  id: number;
  text: string;
}

// 继承Item接口,只需新增items属性
interface NestedItem extends Item {
  items: Item[];
}

// 使用优化后的类型
const myItem: NestedItem[] = [{
  id: 1,
  text: 'hello',
  items: [{
    id: 1,
    text: 'world'
  }]
}];

2. 递归接口(支持无限嵌套)

如果你的嵌套结构可能是多层级无限延伸的(比如父项的子项也可以包含自己的子项),可以直接定义递归接口,避免拆分多个类型:

interface NestedItem {
  id: number;
  text: string;
  // 用可选属性?支持没有子项的叶子节点
  items?: NestedItem[];
}

const myItem: NestedItem[] = [{
  id: 1,
  text: 'hello',
  items: [{
    id: 1,
    text: 'world'
    // 这里可以继续添加items属性,实现无限嵌套
  }]
}];

3. 交叉类型(类型别名方式)

如果更倾向于使用类型别名而非接口,也可以用交叉类型合并基础属性和子项属性:

type Item = {
  id: number;
  text: string;
};

// 合并Item类型与包含items的对象类型
type NestedItem = Item & {
  items: Item[];
};

const myItem: NestedItem[] = [{
  id: 1,
  text: 'hello',
  items: [{
    id: 1,
    text: 'world'
  }]
}];

这几种方式都能有效避免重复定义id、text这类共享属性,后续新增共享属性时只需修改基础类型即可,大幅减少冗余代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:30:53