admin管理员组文章数量:1406920
I am trying to catch an event after file upload on file input.
JS code:
fileSelected(e: Event) {
if ((<HTMLInputElement>e.target).files !== null && (<HTMLInputElement>e.target).files[0] !== null) {
this.file = (<HTMLInputElement>e.target).files[0];
}
}
And my file variable is defined as null. I want to select the first element of files, but I get the error:
Object is possibly null
I found a solution that you first have to check if it's not empty, but I get the same error on if statement itself. Any ideas?
I am trying to catch an event after file upload on file input.
JS code:
fileSelected(e: Event) {
if ((<HTMLInputElement>e.target).files !== null && (<HTMLInputElement>e.target).files[0] !== null) {
this.file = (<HTMLInputElement>e.target).files[0];
}
}
And my file variable is defined as null. I want to select the first element of files, but I get the error:
Object is possibly null
I found a solution that you first have to check if it's not empty, but I get the same error on if statement itself. Any ideas?
Share Improve this question edited Jul 7, 2020 at 10:27 The50 asked Jul 7, 2020 at 10:20 The50The50 1,1884 gold badges25 silver badges57 bronze badges1 Answer
Reset to default 10That is because TypeScript cannot perform type narrowing in the code you've shared. If you (1) assign them to variables and (2) add guard clauses to your logic to enforce non-null value checks, that should fix the issue:
fileSelected(e: Event) {
const target = e.target as HTMLInputElement;
const files = target.files;
// Guard clause to catch cases where `files` or `files[0]` is falsy (null included)
if (!files || !files[0])
return;
// At this point, both `files` and `files[0]` will be non-null
// And `files` will have an inferred type of `FilesList` instead of `FilesList | null`
this.file = files[0];
}
本文标签: javascriptVuejsTS object is possibly 39null39 on file inputStack Overflow
版权声明:本文标题:javascript - Vue.js + TS object is possibly 'null' on file input - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744971554a2635264.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论