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

相关推荐
q***7482 小时前
Spring Boot环境配置
java·spring boot·后端
喝拿铁写前端2 小时前
从面条代码到抽象能力:一个小表单场景里的前端成长四阶段
前端·设计模式·架构
LXA08092 小时前
Vue 3中使用JSX
前端·javascript·vue.js
执携2 小时前
Vue Router (历史模式)
前端·javascript·vue.js
superlls2 小时前
(Spring)Spring Boot 自动装配原理总结
java·spring boot·spring
是梦终空2 小时前
vue下载依赖报错npm ERR node-sass@4.14.1 postinstall: `node scripts/build.js`的解决方法
javascript·npm·vue·node-sass·vue依赖
依米_2 小时前
一文带你剖析 Promise.then all 实现原理,状态机、发布订阅模式完美实现异步编程
javascript·设计模式
陈陈小白2 小时前
npm run dev报错Error: listen EADDRINUSE: address already in use :::8090
前端·npm·node.js·vue