1

I have a stopwatch method that has several properties, I want no one to be able to access them from outside the class, I made them private, but it is still possible to access them and their value can be changed. what do I do?

class StopWatch {
    private duration: number = 0;
    private status: string = 'stopped';
    private currentTime: number = 0;
    start () {
        if (this.status == 'started') {
            throw new Error("already started!");
        }
        this.currentTime = Date.now();
        this.status = "started";
    }
    stop() {
        if (this.status == "stopped") {
            throw new Error("already stopped!");
        }
        this.duration = Date.now() - this.currentTime + this.duration;
        this.status = "stopped";
        console.log((this.duration / 1000).toFixed(1));
    }
    reset() {
        if (this.status == 'started') {
            this.stop();
        }
        this.duration = 0;
    }
}
const obj = new StopWatch();
arta
  • 25
  • 4
  • Please visit the below thread on how to make a truly private member inside the class which cannot be accessible as a member of the class https://stackoverflow.com/questions/12713659/why-can-i-access-typescript-private-members-when-i-shouldnt-be-able-to – Hrusikesh Jan 01 '23 at 07:41

1 Answers1

1

As pointed out by Hrusikesh in the question comments, TypeScript visibility modifiers are enforced only at compile time. At runtime, your class members are always accessible like any JavaScript object properties:

Like other aspects of TypeScript’s type system, private and protected are only enforced during type checking.

But there are now JavaScript class private features: just prefix the member name with a hash (#), and it will be truly "private", i.e. not accessible from outside the class, even after compilation, since it is enforced by JavaScript:

class StopWatch2 {
    #duration: number = 0;

    method() {
        console.log("method", this.#duration);
    }
}

const obj2 = new StopWatch2();
obj2.method();
// [LOG]: "method",  0 

console.log("obj2", obj2.#duration); // Error: Property '#duration' is not accessible outside class 'StopWatch2' because it has a private identifier.
// Does not even run!

Playground Link

ghybs
  • 47,565
  • 6
  • 74
  • 99