Tommie Jones
Tommie Jones

Reputation: 1011

typescript and dealing with FileReader

I am trying to read a file on the client side as an array buffer. Here is my code.

for (var index = 0; index < input.files.length;index++) {
  let reader = new FileReader();
  console.log(input.files[index].name);
  reader.onload = () => {
    var data:ArrayBuffer = reader.result;
    console.log(data.toString().length);
  }
  reader.readAsArrayBuffer(input.files[index])
}

However my editor complains that reader.result returns (string | ArrayBuffer)

However if I remove type type from the data. I am unable to use ArrayBuffer specific methods like byteLength.

How do I force the reader.result to be an ArrayBuffer?

Upvotes: 0

Views: 2760

Answers (1)

Devansh J
Devansh J

Reputation: 4194

Well you know TS is pretty dope xD. Write your code like you would normally write and it will interpret your code and things will roll.

function foo() {
    return (
        Math.random() < 0.5
            ? "damn dis shit wild"
            : new ArrayBuffer(1024)
    )
}

let bar = foo(); // string | ArrayBuffer
if (bar instanceof ArrayBuffer) {
    // bar is only ArrayBuffer in this block :O *.*
    bar.byteLength; // <-- no error
} else {
    bar.startsWith("damn") // <-- no error
}

Here's a demo. I guess this is what you wanted?

Btw you also mentioned by "force" huh so normal assertion would work too, but is not recommended because it can give runtime errors if bar is string.

function foo() {
    return (
        Math.random() < 0.5
            ? "damn dis shit wild"
            : new ArrayBuffer(1024)
    )
}

let bar = <ArrayBuffer>foo();
bar.byteLength; // <-- no error

Demo

Upvotes: 1

Related Questions