0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

OK this worked but I have no idea how the if statement is evaluated at compile time.
@TommieJones Well it's not actually getting evaluated. TS uses the abstract syntax tree to do this. But it's very basic, meaning writing if ([bar instanceof ArrayBuffer][0] === true) instead of if (bar instanceof ArrayBuffer) will not work even tho it does the same thing.
Someone upvoted this, so I'm getting back to the above comment and it's important to mention the way it works is instanceof is a "type guard" in TS, you can make you own with is. so the above comment is not very accurate, it does kinda get "evaluated", not in the wild but in the type context like how all complex types do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.