1

I have this custom simple class:

class U8a extends Uint8Array {
  logMe() {
    return this.subarray(0);
  }
}

And I ran this code:

const u = new U8a([1, 2, 3]);
console.log(u.logMe());

Expected result:

Uint8Array [ 1, 2, 3 ]

Actual result:

U8a [Uint8Array] [ 1, 2, 3 ]

Is it possible to return the result as an Uint8Array only?

5
  • Are you sure this is a typescript, not merely javascript question? Commented Oct 23, 2018 at 14:46
  • What is the problem u instanceof Uint8Array => true you just extend so the u is Uint8Array object Commented Oct 23, 2018 at 14:47
  • @malbarmawi Now I can do u.logMe().logMe(). I want to disable this. Commented Oct 23, 2018 at 14:50
  • Why would you expect Uint8Array? That's not what it is: "The subarray() method returns a new TypedArray on the same ArrayBuffer store and with the same element types as for this TypedArray object." Plus it'd make your logging explicitly incorrect. You could use #from and create a new array. Commented Oct 23, 2018 at 14:52
  • @DaveNewton Yes, that's what I expected too. Hence this question, the title translates to: is it possible to actually return an Uint8Array on the same ArrayBuffer store? Commented Oct 23, 2018 at 14:55

1 Answer 1

1

Update logMe method to return new instant of Uint8Array so will not have the logMe method.

class U8a extends Uint8Array {
  logMe() {
    return new Uint8Array(this.entries());
  }
}

const u = new U8a([1, 2, 3]);
const u2 = u.logMe();
console.log(u2.logMe()); throw Uncaught TypeError: u2.logMe is not a function
Sign up to request clarification or add additional context in comments.

Comments

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.