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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.