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

TypeScript如何将IVertex与IEdge的格式化方法重构为单个通用函数

TypeScript 通用节点格式化方法实现

原有问题说明

之前的错误写法核心问题有两个:

  • 错误解构了临时生成的{ node, name: '' }对象,将原节点嵌套到了node属性下,不符合输出结构要求
  • 没有对联合类型IVertex | IEdge做类型收窄,TypeScript无法识别可解构的属性,导致类型报错

正确实现方案

通过in操作符判断节点是否存在name属性,即可区分两种节点类型,TypeScript会自动完成类型收窄,避免类型错误:

// 原有类型定义
export type IVertex = {
  id: string
  name: string
}

export type IEdge = {
  source: string
  target: string
}

// 通用格式化方法
function formatNodes(nodes: Array<IVertex | IEdge>) {
  return nodes.map(node => {
    // 类型收窄:判断当前是IVertex类型
    if ('name' in node) {
      const { name, ...rest } = node
      return { data: rest }
    }
    // 剩下的就是IEdge类型,直接返回
    return { data: node }
  })
}

如果需要更严格的类型安全,可以配合泛型和单独的类型守卫实现:

// 类型守卫,明确类型判断逻辑
function isIVertex(node: IVertex | IEdge): node is IVertex {
  return 'name' in node
}

// 带泛型的通用方法,输入输出类型关联
function formatNodes<T extends IVertex | IEdge>(nodes: T[]) {
  return nodes.map(node => {
    if (isIVertex(node)) {
      const { name, ...rest } = node
      return { data: rest }
    }
    return { data: node }
  })
}

两种实现都满足需求:仅对IVertex类型节点剔除name字段,IEdge节点保持原结构返回,没有任何类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:39:03