Auto-Accessor Fields Compile To Accessors

Declare class state with the accessor keyword, read the generated getter and setter, and convert Celsius to Fahrenheit through the accessor pair.

TypescriptConfig Management

Code

typescriptsnippet
26 lines
class Temperature {
  accessor celsius = 0;

  get fahrenheit(): number {
    return (this.celsius * 9) / 5 + 32;
  }

  set fahrenheit(value: number) {
    this.celsius = ((value - 32) * 5) / 9;
  }
}

const temperature = new Temperature();
temperature.celsius = 25;
console.log("celsius:", temperature.celsius);
console.log("fahrenheit:", temperature.fahrenheit);

temperature.fahrenheit = 212;
console.log("after boiling point:", temperature.celsius);

const descriptor = Object.getOwnPropertyDescriptor(
  Temperature.prototype,
  "celsius",
);
console.log("has getter:", typeof descriptor?.get === "function");
console.log("has setter:", typeof descriptor?.set === "function");

How the snippet works

Auto-Accessor Fields Compile To Accessors is built around the class Temperature.

Top-level bindings temperature, descriptor hold the demo state — nothing sits inside a function scope.

Applying it

The demo output is labeled (celsius:, fahrenheit:, after boiling point:), so each line in the output traces back to its producing call.

Statements that matter

return (this.celsius * 9) / 5 + 32;

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Its state lives in module-level bindings: `temperature`, `descriptor`.