Search code examples
typescriptuint8array

Typescript get Int8Array from ArrayBuffer


I'm reading a file as ArrayBuffer with this code:

 var reader: FileReader = new FileReader();
 reader.readAsArrayBuffer(file);
 reader.onloadend = function (e) {
    var fileContent = reader.result;
    ...
 }

I need to get the content as byte array but I can't do it. If I try to convert in this way:

var byteArray = new Int8Array(fileContent);

I get this error: impossible to assign string to ArrayBuffer | ArrayLike | SharedArrayBuffer. Is fileContent a string? I think it should be an ArrayBuffer because I'm using readAsArrayBuffer. Is there a way to get byte array from uploaded file? Thanks


Solution

  • You need to add type assertion

    var byteArray = new Int8Array(fileContent as ArrayBuffer);