Search code examples
typescriptencapsulation

TypeScript compiler allows calling non-existing getter. Is this a bug in the compiler?


In short, I am very confused why this code compiles without error:

class Foobar {
    #data = 0
    set data(val: number) { this.#data = val }
    // (Notice there is no getter for "data")
}
let foobar = new Foobar()
// Call the setter for data, no problemo
foobar.data = 123
// Call the getter for data, compiler should not allow this imo
console.log(foobar.data) // Prints "undefined"
  1. Is this a bug in the typescript compiler? I can't find anywhere that this issue is mentioned. Or is my example working as intended (did I miss something?).
  2. Is there some way (using eslint rules or tsc) to catch this erroneous code?

Solution

  • There is a related but not exactly the same issue in TypeScript github repo and the answer is that this is the defined ES6 class behavior.

    There is a linter rule to check that you have a setter without getter or setter without getter. I don't know if there is any rule that checks for calling a getter that doesn't exist. But you can define a getter that throws an Error, so at least in runtime you will see errors and unit tests would fail.