【问题标题】:'File' object does not have a 'path' property. (TypeScript)“文件”对象没有“路径”属性。 (打字稿)
【发布时间】:2019-09-07 17:53:39
【问题描述】:

我将来自浏览器的File 对象(通过拖放)传递给这样的函数:

// .... logic here...
accept(file)

public static accept(file: File) {
   console.log(file)
   /* prints:
      => lastModified: 1555453309243
         lastModifiedDate: Wed Apr 17 2019 01:21:49 GMT+0100 (GMT+01:00) {}
         name: "test.txt"
         path: "test.txt" --> as you can see there is a path variable in here.
         size: 16
         type: "text/plain"
         webkitRelativePath: ""
         __proto__: File
   */

   console.log(file.name) // => prints 'test.txt'
   console.log(file.size) // => prints '16'
   console.log(file.path) // => !! error given. path does not exists in File object. Also IDE does not show this parameter in IDE autocomplete list.
}

给出的错误:

Property 'path' does not exist on type 'File'.ts(2339)

为什么File 没有path 参数?如何确保路径存在? File 还有其他类型吗?这是一个 HTML5 拖放。

如果我这样做:

public static accept(file: any) {
   alert(file.path);
}

显示相对路径:

【问题讨论】:

  • 我可以访问它。这是 HTML5 拖放项目。我已经更新了这个问题。看看这个。我只是不能使用静态类型。我怎样才能欺骗 IDE 和 webpack,它里面有一个 path。?
  • 如果属性那里,您可以随时通过(file as any).path访问它。
  • @mbojko 是的,成功了。谢谢!你可以把它写成答案。
  • 理想情况下,您应该制作自己的界面,如interface MyFile extends File { path: string; /* etc */ } 并使用它。但是,在哪里记录了 File 具有 path 属性?如果您只支持某些特定或非标准环境,您应该知道。
  • 啊,所以 React-Dropzone 正在添加这个属性。我认为这应该是 React-Dropzone 的 TypeScript 类型的一部分......也许是 DropZoneFileDropZoneFolder 扩展 File 并带有可选的 path 属性?由于他们还没有在库中完成它,所以我想您需要为自己的代码执行此操作。

标签: javascript html typescript


【解决方案1】:

对于使用react-dropzone 的其他人,他们似乎正在从这个库file-selector 获得FileWithPath 的输入

请参见此处的第 3 行: https://github.com/react-dropzone/react-dropzone/blob/master/typings/react-dropzone.d.ts

您可以在任何需要的地方从react-dropzone 导入这个FileWithPath

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-31
    • 2019-10-03
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 2020-01-19
    相关资源
    最近更新 更多