Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
Locking down a TypeScript class so that it is final and all invariants are guaranteed, even at runtime?

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!