Is it possible to export in a different manner?
I have a module that exports an object, which may change. The internal access to the object should be more permissive than external:
// Module A.
export let obj = {
publiclyAvailable: 0,
noTouchy: 0,
};
const func1 = () => { obj.noTouchy; /* Ok. */ };
const func2 = () => { /* reassign `obj` */ };
// Module B.
import { obj } from './A.js';
obj.publiclyAvailable; // Ok.
// obj.noTouchy; // No!
Currently, I am using an unnecessary indirection and code interference into 'emit':
// Module A.
let objContainer = {
_realObj: {
publiclyAvailable: 0,
noTouchy: 0,
},
get obj() { return this._realObj; },
set obj(v) {
this._realObj = v;
obj = v;
},
};
export let obj: { publiclyAvailable: number } = objContainer.obj;
However, writing objContainer.obj
every time serves no real purpose.
There is also a trick with asserting, but it only works on the top level:
// Module A.
const hack: (x: typeof obj) => asserts x is { publiclyAvailable: number; noTouchy: number } = () => void 0;
export let obj: {
publiclyAvailable: number
} = (() => ({
publiclyAvailable: 0,
noTouchy: 0,
}))();
hack(obj);
obj.noTouchy; // Works!
const func1 = () => { obj.noTouchy; /* Fails. */ };
Edit: Considered a less cumbersome way (although it still interferes needlessly):
// Module A.
let _obj = {
publiclyAvailable: 0,
noTouchy: 0,
}
export const obj = new Proxy({} as { publiclyAvailable: number }, {
get(_, p: keyof typeof _obj) { return _obj[p]; },
/* ... all other handlers, because that's what `Proxy` needs ... */
});