#package private fields

15 messages · Page 1 of 1 (latest)

green copper
#

Is it possible to have a field in a class that is not accessible from the outside, but still accessible by other classes that are defined within the same file / package / folder where the class is declared?

I wish to use the field internally in my library, but it is not supposed to be accessible for library users.

Simplified example from my code:

class RunningAnimation {
    package private onDraw: (state: Object) => void;
}

class AnimationSystem {
    private runningAnimations: Set<RunningAnimation>;

    public draw(): void {
        for (const animation of this.runningAnimations) {
            // this should be accessible
            // only from within the lib
            // but not to library users
            animation.onDraw({ foo: "bar" });
        }
    }
}
visual cosmos
#

I don't think JS really has that sort of feature, no.

#

You might be able to mimic it with a WeakMap keyed by the instance, though.

green copper
#

I could of course pull the onDraw field outside of the RunningAnimation class and store a [onDraw, RunningAnimation] in the Set

visual cosmos
#

Or you might be able to 'fake it's at the type level. But JS itself doesn't have "package private"

green copper
#

I exclusively plan to use the lib from typescript anyways, but if it doesn't exist thats fine.

#

In that case I need another storage class and a Map with some kind of key to internally index animations.

#

Thx a lot of course 🙂

visual cosmos
#

Ah there's --stripInternal at the type level.

green copper
#

OH, that looks like it is exactly what I need

visual cosmos
green copper
#

it's fine if it is accessible to JS people. They are in unsafe-land anyways.

#

Nice, I did not find that in like half an hour of searching!

#

Thanks a million ❤️

green copper
#

/resolved