Class Fields Define Instead Of Assign
ES2022 class fields create own properties — TypeScript rejects a subclass field over a base accessor (TS2610), so route writes through assignments instead.
Code
class Temperature {
#celsius = 0;
get celsius(): number {
return this.#celsius;
}
set celsius(value: number) {
console.log('setter ran:', value);
this.#celsius = value;
}
}
// Field declarations use define semantics: they create own properties.
// Plain JavaScript would let a subclass field silently shadow the base
// accessor, so TypeScript refuses it at compile time instead:
// class Snapshot extends Temperature {
// celsius = 21.5; // TS2610: accessor overridden as an instance property
// }
// To write through the base setter, assign — never re-declare a field.
// Assignments in constructors and methods hit the accessor on the prototype.
class Warm extends Temperature {
constructor() {
super();
this.celsius = 21.5;
}
}
const warm = new Warm();
warm.celsius = 30;
console.log('final read:', warm.celsius);Output
Captured from a sandboxed run of this snippet in the build pipeline.
setter ran: 21.5
setter ran: 30
final read: 30What runs when
All of the logic lives in the classes Temperature and Warm.
The file’s state is a handful of top-level bindings: warm.
What to watch for
- The install step does not exist — APIs come with the platform.
Using it
The run prints setter ran:, final read: — each prefix names the step that produced it.
Key statements
return this.#celsius;
Interactive Tools for This Topic
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `warm`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.