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 等),可以提供更多信息,我可以给出更精准的建议

相关推荐
驰骋工作流5 小时前
流程引擎BPM设计之:流程消息
java·工作流引擎·bpm·jflow·ccflow
dogstarhuang5 小时前
从 0 到 1 搭建可收费的 API 开放平台(实战)
java·架构·api
promiseThen5 小时前
5 分钟上手 Markdown:标题到表格、代码块与简历实战
前端
web66liang5 小时前
webpack4+vue2项目使用 sass-embedded 导致的 DockerfIle 构建失败的问题
前端
Strayer5 小时前
拓扑管网 3D 可视化大屏demo:科技感(地图 + 拓扑 + 3D 空间)
前端·three.js·数据可视化
葬送的代码人生5 小时前
从 Vue 到 React:Tailwind CSS 布局 + BFF 代理实战
前端·react.js·架构
摸鱼老王不带85 小时前
不用后端,纯前端读出"网站眼里你的真实出口 IP"——聊聊 Cloudflare 的 cdn-cgi/trace
前端
程序员黑豆5 小时前
鸿蒙开发入门:Row 和 Column 布局组件详解
前端·harmonyos
VortMall6 小时前
『平台去经营化』平台治理能力全新重构|VortMall微服务商城系统v1.3.10
java·大数据·微服务·商城系统·开源商城·vortmall·去经营化
hoLzwEge6 小时前
前端环境变量配置指南:.env 文件详解
前端·前端框架