Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

typescript中原生对象没有某属性的情况

比如

<input type="file" name="root" ref={inputEl} onChange={onInputChange} />
const onInputChange = (e: any) => {
// 下面一行提示错误
    const files: Array<File> = [...e.target.files].map(item=>item.webkitRelativePath))
    console.log(files)
  }

提示的错误是

类型“File”上不存在属性“webkitRelativePath”

但实际是File文档上有这个属性的

这种情况如何处理?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

你用了非标准属性,可以利用 TS interface 重复声明会合并的特点自己追加额外属性。至于运行时是否符合类型定义,需要你自己负责。

declare global {
    // 低版本的 TS FileList 不是 Iterable 的,自己加一个
    interface FileList {
        [Symbol.iterator](): Iterator<File>;
    }

    interface File {
        webkitRelativePath: string;
    }
}

 const onInputChange = (e: Event) => {
    const inputEl = e.currentTarget as HTMLInputElement;
    const files: string[] = [...inputEl.files!].map(item=>item.webkitRelativePath);
    console.log(files)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...