tsfile.raw提示

问:

类型"{ readonly lastModified: number; readonly name:string; readonly webkitRelativePath: string; readonly size: number; readonly type: string; arrayBuffeer: () => Promise<ArrayBuffer>; slice: (start?: number, contentType?: string) => Blob; stream: () =>ReadableStream<...>; text: () => Promise<...>; } |{ ...."上不存在属性"raw"。 const file = item.file?.raw || item.file

回答:

你遇到的 TypeScript 错误:

类型"{ readonly lastModified: number; readonly name: string; ... } | { ... }"上不存在属性"raw"。

是因为你尝试访问 item.file?.raw,但 item.file 的类型是标准的 File 或 Blob 对象(或其联合类型),而这些原生对象没有 raw 属性


问题分析

在 Web 开发中,特别是使用一些 UI 库(如 Element Plus、Ant Design Vue 等)上传组件时,上传项(upload item)中的 file 字段有时会被包装成一个包含原始 File 对象的对象,例如:

复制代码
{
  raw: File,   // 原始 File 对象
  name: string,
  status: string,
  // ...
}

但在你的代码中,item.file 本身已经是 File 对象了 ,而不是这种包装对象。因此 item.file.raw 是无效的。


解决方案

✅ 正确写法(根据实际数据结构)
  1. 如果你的数据结构是:

    复制代码
    item = {
      file: File  // 直接是 File 对象
    }

    那么直接使用:

    复制代码
    const file = item.file;
  2. 如果你的数据结构是:

    复制代码

    Ts

    编辑

    复制代码
    item = {
      file: {
        raw: File,  // 包装对象
        name: 'xxx',
        // ...
      }
    }

    那么才需要:

    复制代码

    Ts

    编辑

    复制代码
    const file = item.file.raw;
  3. 如果你不确定结构,且想兼容两种情况(不推荐,但可行):

    复制代码

    Ts

    编辑

    复制代码
    const file = (item.file as any)?.raw || item.file;

    但更好的方式是使用类型守卫:

    复制代码

    Ts

    编辑

    复制代码
    function isWrappedFile(fileOrWrapper: any): fileOrWrapper is { raw: File } {
      return fileOrWrapper && fileOrWrapper.raw instanceof File;
    }
    
    const file = isWrappedFile(item.file) ? item.file.raw : item.file;

如何确认你的 item.file 结构?

在浏览器控制台打印一下:

复制代码

Ts

编辑

复制代码
console.log(item.file);
  • 如果看到 { name: "...", size: ..., type: ... } → 这就是原生 File,没有 raw
  • 如果看到 { raw: File, name: "...", status: "..." } → 这是 UI 库包装的对象,有 raw

总结

你的错误是因为 误以为 item.file 是包装对象,其实它已经是 File 本身。请根据实际数据结构调整代码:

复制代码

Ts

编辑

复制代码
// 大多数现代场景下,直接这样即可:
const file = item.file;

除非你明确知道使用的是某个 UI 库的 upload 组件且其返回格式包含 .raw

如有具体 UI 框架(如 Element Plus、Naive UI、Ant Design 等),可以提供更多信息,我可以给出更精准的建议

相关推荐
独自破碎E2 分钟前
数组列表中的最大距离
java
猿小羽4 分钟前
基于 Spring AI 与 Streamable HTTP 构建 MCP Server 实践
java·llm·spring ai·mcp·streamable http
Hexene...5 分钟前
【前端Vue】npm install时根据新的状态重新引入实际用到的包,不引入未使用到的
前端·vue.js·npm
大模型微调Online6 分钟前
深度复盘:Qwen3-4B-Instruct-2507微调实战——打造“快思考、强执行”的 ReAct IoT Agent
java·后端·struts
铁蛋AI编程实战8 分钟前
Agentic AI/GPT-4o替代/Spring AI 2.0/国产大模型轻量化
java·人工智能·spring
weixin_704266059 分钟前
Maven入门:构建与依赖管理全解析
java·maven
cyforkk10 分钟前
14、Java 基础硬核复习:数据结构与集合源码的核心逻辑与面试考点
java·数据结构·面试
2301_7806698611 分钟前
Vue(入门配置、常用指令)、Ajax、Axios
前端·vue.js·ajax·javaweb
码农幻想梦11 分钟前
Vue3入门到实战【尚硅谷】
前端·vue
零度@13 分钟前
专为 Java 开发者 整理的《Python编程:从入门到实践》前8章核心内容
java·开发语言·windows·python