What is the best way of making a TypeScript class final, and ensure that all its invariants are guaranteed, even during runtime (when it might be accessed by arbitrary JavaScript code)?
A simple example of what I want to do is the following MutableInt class:
export class MutableInt {
static {
Object.setPrototypeOf(MutableInt.prototype, null);
Object.freeze(MutableInt.prototype);
Object.freeze(MutableInt);
}
#value : number
constructor (value : number = 0) {
if (new.target !== MutableInt) throw new Error("MutableInt is final");
if (!Number.isInteger(value)) throw new Error(`Integer expected, found: ${value}`);
this.#value = value;
Object.freeze(this);
}
get value(): number {
return this.#value;
}
set value(v) {
if (!Number.isInteger(v)) throw new Error(`Integer expected, found: ${v}`);
this.#value = v;
}
}
Is MutableInt properly locked down? Or is there something wrong or missing with this approach?
Edit: To clarify, I am not only interested in final decorators etc., I am interested in all sorts of ways MutableInt could be tampered with in a way such that it is not safe to use it. It seems in TypeScript / JavaScript there are a million attack vectors how an API can be compromised, and I am wondering if the above code considers all of them, or misses something.