Hello everyone I'm trying to figure out how to upload a document in React + TypeScript and I have a state with the selected file set up by the onFileChange event listener like so:
onFileChange(event: React.ChangeEvent<HTMLInputElement>) {
if (event !== null && event.target !== null && event.target.files !== null) {
this.setState({selectedFile: event.target.files[0]});
}
};
And so far that works, but when I construct the FormData object it errors out.
if (this.state !== null && this.state.selectedFile !== null) {
const formData = new FormData();
formData.append(
"foo",
this.state.selectedFile,
this.state.selectedFile.name
);
}
But I'm getting this error:
TS2345: Argument of type 'null' is not assignable to parameter of type 'string | Blob'
I figured I already had checked for nullability for this.state.selectedFile and this.state. Any reason why this isn't working? Am I interpreting this wrong?
event.target.filescould still have.length == 0. AFAIK, TypeScript's flow-analysis still doesn't consider array lengths.this.state.selectedFile? Do you have strict nulls on or off?state = { selectedFile: null };" - that's the problem. Give your initial state a better type.