When using JavaScript strict mode (either through the "use strict" directive or in contexts where strict mode is always enabled, like inside classes), attempting to assign to a getter-only property will result in a runtime error. This means that your code will trigger the expected runtime error:
"use strict";
class Computed<V> {
_value: V;
constructor(v: V) {
this._value = v; // Added for easier initialization
}
get value() {
return this._value;
}
}
const v = new Computed(123);
v.value = 2; // error
// compile-time error: Cannot assign to 'value' because it is a read-only property.
// also, RUNTIME ERROR! 💥 TypeError: setting getter-only property "value"
If the above is not satisfactory, you can explicitly create a setter that throws your desired error, especially since TypeScript 5.1 introduced support for unrelated types for getters and setters. The getter type remains the same, while the setter requires the impossible "never" type to prevent compile-time calls:
class Computed<V> {
_value: V;
constructor(v: V) {
this._value = v;
}
set value(x: never) {
throw new TypeError("hey, don't do that")
}
get value(): V { // Explicit return type annotation
return this._value;
}
}
const v = new Computed(123);
v.value = 2; // error
// compile-time error: Type 'number' is not assignable to type 'never'.
// also, RUNTIME ERROR! 💥 TypeError: hey, don't do that
Playground link to code