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

如何从嵌套TypeScript接口中移除Workplace的id和name属性

正确实现嵌套类型修改的方案

你的写法问题在于直接把三个接口平级继承了,这会把Customer、Office、Workplace的属性全部合并到AddCustomer里,完全偏离了修改嵌套结构的需求。要实现目标,需要逐层修改嵌套的子类型:

步骤1:定义修改后的Workplace类型

先创建去掉id和name的Workplace类型:

type AddWorkplace = Omit<Workplace, 'id' | 'name'>;

步骤2:定义修改后的Office类型

基于原Office接口,替换workplaces的类型为上面的AddWorkplace[]:

interface AddOffice extends Omit<Office, 'workplaces'> {
  workplaces: AddWorkplace[];
}

步骤3:定义最终的AddCustomer类型

基于原Customer接口,替换offices的类型为AddOffice[](保留原接口的可选性):

interface AddCustomer extends Omit<Customer, 'offices'> {
  offices?: AddOffice[];
}

验证示例

现在你的示例对象就能完美匹配AddCustomer类型了:

const addCustomerDetail: AddCustomer = {
   id: '123',
   accountId: '123',
   name: 'some name',
   offices: [
      {
         id: '123',
         name: 'some name',
         country: 'UK',
         address: 'Street name',
         zip: '90210',
         description: 'Some Office',
         workplaces: [
            {
               employeeId: '1337'
            }
         ]
      }  
   ]
};

如果不想单独定义中间类型,也可以用嵌套推导简化写法:

interface AddCustomer extends Omit<Customer, 'offices'> {
  offices?: (Omit<Office, 'workplaces'> & {
    workplaces: Omit<Workplace, 'id' | 'name'>[];
  })[];
}

这种写法不需要额外定义AddWorkplace和AddOffice,直接在AddCustomer里修改嵌套的offices结构,效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:06:10