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

Vue2+TypeScript循环Section类型数据时类型识别异常求助

Vue + TypeScript: v-for无法识别Section类型属性,类型推断异常

问题场景

使用Vue结合TypeScript开发时,需要循环遍历接口返回的Section类型数组(每个Section包含Article数组),响应数据结构如下:

[
  {
    "id": 1,
    "name": "Test",
    "articles": [
      {
        "id": 1,
        "name": "Test",
        "price": 1.0,
        "quantity": 1
      }
    ]
  },
  {
    "id": 2,
    "name": "Test 2",
    "articles": [
      {
        "id": 2,
        "name": "Test 2",
        "price": 2.0,
        "quantity": 2
      }
    ]
  }
]

但使用v-for循环时,无法识别section.id等属性,且TypeScript将section的类型推断为string | number | boolean | Date | Article[] | undefined,而非预期的Section类型。

解决方案

1. 明确定义类型

先在代码中声明Article和Section的TypeScript接口,给TypeScript提供明确的类型依据:

// 定义Article类型
interface Article {
  id: number;
  name: string;
  price: number;
  quantity: number;
}

// 定义Section类型,包含Article数组
interface Section {
  id: number;
  name: string;
  articles: Article[];
}

2. 给数据变量显式指定类型

不管是Vue 3的<script setup>还是Vue 2的选项式API,都要给存储接口数据的变量显式声明为Section[]类型,避免TypeScript自动推断出宽泛的联合类型:

Vue 3

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:50:23