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

相关推荐
鹿角片ljp3 小时前
LeetCode 64:最小路径和复盘|二维 DP 与 ACM 模式完整写法
java·数据结构·算法
+VX:Fegn08954 小时前
计算机毕业设计|基于springboot + vue蛋糕店管理系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·课程设计
泡海椒4 小时前
PDF 表格样式优化:jquick-pdf 边框、圆角、背景色
java·开发语言·pdf
半个落月4 小时前
LangChain.js Agent Memory 实战(下):用 Milvus 构建可检索的长期记忆
javascript·langchain
半个落月4 小时前
LangChain.js Agent Memory 实战(上):从内存对话、文件持久化到截断与摘要
javascript·langchain
Nicander5 小时前
我给 Excalidraw 做了一个本地工作区:DrawSpace
前端·开源
景熙55235 小时前
15.Java 8 Stream 流入门到实战
java·开发语言·数据结构
wno7046 小时前
Spring Security权限控制
java·python·spring
杨运交6 小时前
[071][验证码模块]基于Spring拦截器的验证码认证设计思想
java·后端·spring