Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda