“文件”对象没有“路径”属性。(打字稿)

Pra*_*tha 5 html javascript typescript

我将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.
}
Run Code Online (Sandbox Code Playgroud)

给出的错误:

Property 'path' does not exist on type 'File'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

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

如果我这样做:

public static accept(file: any) {
   alert(file.path);
}
Run Code Online (Sandbox Code Playgroud)

它显示了相对路径:

小路

Kit*_*son 19

对于其他使用 的人来说react-dropzone,他们似乎正在FileWithPath从这个库中获取输入内容file-selector

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

FileWithPath您只需从react-dropzone需要的地方导入即可。


小智 15

基特森的回答是正确的。我只是想为那些新接触 Typescript 的人添加实现这个答案的确切方法。如果您刚刚开始使用 Dropzone 文档中的基本示例,您只需添加FileWithPath导入来源react-dropzone并定义来自地图的每个文件的类型。注意这里的两个补充FileWithPath

import { useDropzone, FileWithPath } from "react-dropzone";
 
function Basic(props) {
  const {acceptedFiles, getRootProps, getInputProps} = useDropzone();
 
  const files = acceptedFiles.map((file: FileWithPath) => (
    <li key={file.path}>
      {file.path} - {file.size} bytes
    </li>
  ));
...
Run Code Online (Sandbox Code Playgroud)