I have input
<input
accept="image/*"
id="contained-button-file"
multiple
type="file"
/>
And i want to load the file selected using:
const selectedFile = ( document.getElementById('contained-button-file') as HTMLInputElement ).files[0];
But Typescript complains:
TS2531: Object is possibly 'null'.
How can i work around this or make sure it has file selected ( as i want to send it to server ) ?
THanks for help
CodePudding user response:
You can check if files is truthy then get files[0]
const input = document.getElementById('contained-button-file') as HTMLInputElement;
const file = input.files ? input.files[0] : null;
CodePudding user response:
Quick and dirty solution:
const selectedFile = (
document.getElementById('contained-button-file') as HTMLInputElement
).files![0];
This says that files
will not be null, which is true in this case. TS just doesn't know that the input is of type file
.
Error handling solution
const element = document.getElementById('contained-button-file');
if (!element || !(element instanceof HTMLInputElement))
throw Error('Could not retrieve file input element');
const input = element as HTMLInputElement;
if (!input.files) throw Error('File input is not of type "file"');
const selectedFile = input.files[0];
Typescript is able to see that you've put these guards in place and knows that the objects cannot be null in the code underneath them.