logoalt Hacker News

wrsyesterday at 8:54 PM1 replyview on HN

I think you're confusing values with types. JS modules can certainly keep a value private, but there's no way for them to expose an opaque type, because that concept simply doesn't exist in JS. The language only has a few types, and you don't get to make more of them. TypeScript adds a lot of type mechanism on top, but because it's restricted to being strippable from the actual JS code, it doesn't fundamentally change that.


Replies

hackrmntoday at 8:26 AM

Here's an opaque type wrapping numbers, in JavaScript:

    class Age {
        #value;
        constructor(value) {
            if(typeof value != "number") throw new Error("Not a number");
            this.#value = value;
        }
    }