【发布时间】: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 类型的一部分......也许是
DropZoneFile或DropZoneFolder扩展File并带有可选的path属性?由于他们还没有在库中完成它,所以我想您需要为自己的代码执行此操作。
标签: javascript html typescript