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

Vue3中v-for遍历item为unknown的TypeScript报错解决

解决Vue3 + TypeScript中v-for遍历props数组时item类型为unknown的问题

你遇到的TypeScript错误是由类型定义和props声明的细节问题导致的,以下是具体修复方案:

问题根源

  1. 接口Item中误用了大写的String/Boolean(构造函数类型),TypeScript类型注解需使用小写的原始类型string/boolean,大写构造函数类型会干扰类型推导逻辑。
  2. 原代码中defineProps里的type字段写为Object,但items是数组类型,这个错误直接导致TypeScript无法正确识别数组元素的类型。

修复步骤

1. 修正接口类型定义

将接口内的构造函数类型替换为原始类型:

interface Item {
  href: string;
  active: boolean;
  text: string;
}

2. 修正props声明(两种方案可选)

方案一:修复原对象式声明

保持原有写法,修正type字段的类型指向:

<script setup lang="ts">
import NavLink from '@/Components/NavLink.vue';
import { PropType } from 'vue'

interface Item {
  href: string;
  active: boolean;
  text: string;
}

const props = defineProps({
  items : {
    type: Array as PropType<Item[]>, // 将Object改为Array,匹配数组类型
    required: true
  }
});
</script>

方案二:改用类型声明式defineProps(更推荐)

这种写法更贴合TypeScript风格,类型推导更精准:

<script setup lang="ts">
import NavLink from '@/Components/NavLink.vue';

interface Item {
  href: string;
  active: boolean;
  text: string;
}

// 直接通过类型声明定义props
const props = defineProps<{
  items: Item[];
}>();
</script>

3. 模板部分无需修改

完成上述修复后,模板中的item会被正确推断为Item类型,之前的TypeScript错误会自动消除。

额外提示:v-for的key尽量避免使用index,如果item.href是唯一值,建议改用:key="item.href",可提升列表渲染性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:20:38