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

TypeScript如何从带可选字段的接口正确派生嵌套属性类型

报错原因

connected_account被标记为可选属性后,IEmployee['settings']['external_payment']['connected_account']的推导结果是「定义的账户对象类型 | undefined」的联合类型。直接在这个联合类型上访问status属性时,TS会判定存在从undefined上读取属性的风险,因此抛出tsserver 2339类型错误:
tsserver 2339类型错误截图
错误提示原文:

[tsserver 2339] [E] Property 'status' does not exist on type '{ status:
string; last4?: string | undefined; account_type_code?: string | undefined;
bank_account_name?: string | undefined; verification_method?: string |
undefined; institution: { ...; }; } | undefined'.
解决方法

核心思路是先排除联合类型里的undefined分支,再读取status的类型,推荐两种可落地的写法:

  • 写法1:使用TS内置NonNullable工具类型(最简洁)
    NonNullable会自动剔除联合类型中的null和undefined,直接拿到目标对象类型后再取属性:
export interface Employee {
  settings: {
    external_payment: {
      connected_account?: {
        status: NonNullable<IEmployee['settings']['external_payment']['connected_account']>['status'];
      };
    },
  },
}
  • 写法2:抽离公共类型别名(可读性更高)
    如果后续还要复用connected_account下的其他字段,可以先抽离类型别名,避免重复写长链式索引:
// 先拿到connected_account的联合类型,排除undefined后得到完整对象类型
type NonNullConnectedAccount = NonNullable<IEmployee['settings']['external_payment']['connected_account']>;

export interface Employee {
  settings: {
    external_payment: {
      connected_account?: {
        status: NonNullConnectedAccount['status'];
        // 后续要取其他字段直接引用即可,比如last4: NonNullConnectedAccount['last4']
      };
    },
  },
}

不建议用@ts-ignore、非空断言!这类方式绕过校验,这类写法会切断两个接口的类型关联,后续如果原IEmployee接口中status的类型发生变更,Employee接口不会同步得到类型提示,埋下类型安全隐患。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 02:51:58