According to TypeScript types definitions, the type of ProgressEvent.target.result could be string, ArrayBuffer or null.
What I need is, the function which encodes the file to base64 which is type string.
But what I have to do when it is null or instance of ArrayBuffer?
async function encodeFileToBase64(targetFile: File): Promise<string> {
const fileReader: FileReader = new FileReader();
fileReader.readAsDataURL(targetFile);
return new Promise<string>((resolve: (encodedFile: string) => void, reject: (error: Error) => void): void => {
fileReader.onload = (filedHasBeenReadEvent: ProgressEvent<FileReader>): void => {
const fileReadingResult: string | ArrayBuffer | null | undefined = filedHasBeenReadEvent.target?.result;
if (isEitherUndefinedOrNull(fileReadingResult)) {
reject(new Error("Failed to encode the file."));
return;
}
resolve(
fileReadingResult instanceof ArrayBuffer ?
String.fromCharCode.apply(null, new Uint8Array(fileReadingResult)) :
fileReadingResult
);
};
});
}
The "Failed to encode the file." error has not enough details.
- What means
null? - Why has it occured?
- What is required to do to have the
stringtype next time?
Same sub-question about ArrayBuffer.
Additionally, I have TypeScript error in
String.fromCharCode.apply(null, new Uint8Array(fileReadingResult))
S2345: Argument of type Uint8Array is not assignable to parameter of type number[] Type Uint8Array is missing the following properties from type number[] : pop, push, concat, shift , and 5 more.

You don't need to use
event.target, asevent.targetis the "a reference to the object onto which the event was dispatched", so it's just thefileReaderitselfThe type of
fileReader.resultdepends on the operation you call over it. Depending on the operation, FileReader can be one of:loadevent, if means thatfileReader.errorhas the error value.Personally I would recommend a wrapper of the whole FileReader like https://www.npmjs.com/package/@tanker/file-reader or a typed variant of MDN example:
https://developer.mozilla.org/en-US/docs/Web/API/Event/target#example