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

Vue中访问TypeScript联合类型属性报错:Property 'text'不存在

解决Vue中TypeScript联合类型属性不存在的报错

问题原因

DataItem是Text | Link | Html的联合类型,其中Html接口没有text属性,TypeScript无法确保遍历的每个dataItem都包含text字段,因此抛出Property 'text' does not exist on type 'DataItem'的错误。

解决方案

方案1:模板中用in操作符做类型收缩

直接在Vue模板里通过'text' in dataItem判断当前项是否包含text属性,TypeScript会自动将类型收缩为Text或Link,从而安全访问text:

<template v-for="(dataItem, index) in item.data" :key="index">
  <p v-if="'text' in dataItem" :class="itemClasses">
    {{ dataItem.text }}
  </p>
</template>

方案2:自定义类型守卫函数

如果需要更复杂的判断逻辑,可在组件脚本中定义类型谓词函数,明确标记当前项的类型:

// <script setup> 中的代码
import type { DataItem } from './your-types-file';

function hasText(item: DataItem): item is Text | Link {
  return 'text' in item;
}

之后在模板中调用该函数:

<template v-for="(dataItem, index) in item.data" :key="index">
  <p v-if="hasText(dataItem)" :class="itemClasses">
    {{ dataItem.text }}
  </p>
</template>

方案3:使用可区分联合类型(推荐)

修改类型定义,给每个接口添加唯一的类型标识字段,让TypeScript能精准识别类型:

export interface Link {
  type: 'link';
  to: string;
  text?: string;
}
export interface Text {
  type: 'text';
  text: string;
}
export interface Html {
  type: 'html';
  html: string;
}
export type DataItem = Text | Link | Html;

然后在模板中通过类型标识判断:

<template v-for="(dataItem, index) in item.data" :key="index">
  <p v-if="dataItem.type === 'text' || dataItem.type === 'link'" :class="itemClasses">
    {{ dataItem.text }}
  </p>
</template>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:58:11