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

TypeScript:对象属性可为对象数组或单个对象时如何设置类型

解决TypeScript中edges既为数组又为单个对象的类型问题

核心方案

把edges定义为单个对象或对象数组的联合类型,再通过自定义类型守卫区分两种场景,让TypeScript能正确推断类型,消除报错。

具体实现步骤

  1. 修正类型定义
    先抽离单个边缘对象的类型,再将edges设为该类型与数组的联合:

    type CategoryEdge = {
      node: {
        name: string;
      };
    };
    
    type CategoriesProps = {
      categories: {
        edges: CategoryEdge | CategoryEdge[];
      };
    };
    
  2. 添加类型守卫函数
    写一个函数帮TypeScript判断edges是否为数组:

    function isEdgeArray(edges: CategoryEdge | CategoryEdge[]): edges is CategoryEdge[] {
      return Array.isArray(edges);
    }
    
  3. 重构组件逻辑
    用类型守卫分支处理两种情况,TypeScript就能准确识别每个分支里的edges类型:

    export default function Categories({ categories }: CategoriesProps) {
      const { edges } = categories;
      return (
        <span className="ml-1">
          under
          {isEdgeArray(edges) ? (
            edges.length > 0 ? (
              edges.map((category, index) => (
                <span key={index} className="ml-1">
                  {category.node.name}
                </span>
              ))
            ) : null
          ) : (
            <span className="ml-1">{edges.node.name}</span>
          )}
        </span>
      );
    }
    

额外优化建议

  • 避免用数组索引作为key,如果node有唯一标识(比如id),改用category.node.id,提升列表渲染稳定性。
  • 优先协调后端统一返回数组格式(哪怕只有一个元素),能大幅简化前端的类型和逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:45:17