To transform the begin
into an accessor property with only a getter, you can create a method called setBegin
:
class LineRange {
constructor(
private _begin: number,
private _end: number
) {
}
get begin(): number {
return this._begin;
}
setBegin(begin: number): void {
this._begin = begin;
}
get end(): number {
return this._end;
}
setEnd(end: number): void {
this._end = end;
}
}
Here is how you can use it:
const lr = new LineRange(0, 0);
console.log(lr.begin); // 0
// lr.begin = 42; <== Would be an error
lr.setBegin(42); // Works
console.log(lr.begin); // 42
You can also define it as an interface (which the implementation above would support if you change the name):
interface LineRange {
readonly begin: number;
setBegin(begin: number): void;
readonly end: number;
setEnd(end: number): void;
}
Check out the live example on the playground
Note:
I prefer not to introduce a getBegin() function just for reading a simple member.
It's important to mention that using an accessor property does technically introduce a function. However, it doesn't require using function call syntax when accessing the property; the function call is implicit.
If you want to avoid this, you can hide the class
and only use the interface type:
interface LineRange {
readonly begin: number;
setBegin(begin: number): void;
readonly end: number;
setEnd(end: number): void;
}
class LineRangeClass implements LineRange {
constructor(
public begin: number,
public end: number
) {
}
setBegin(begin: number): void {
this.begin = begin;
}
setEnd(end: number): void {
this.end = end;
}
}
In usage, ensure to declare lrc
explicitly as LineRange
instead of LineRangeClass
:
const lrc: LineRange = new LineRangeClass(0, 0);
console.log(lrc.begin);
// lrc.begin = 42; <== Would be an error
lrc.setBegin(42); // Works
console.log(lrc.begin);
Keep in mind that without specifying a type for lrc
, it will default to LineRangeClass
, allowing setting the begin
property:
const lrc = new LineRangeClass(0, 0);
console.log(lrc.begin);
lrc.begin = 42; // <== NOT an error, because `lrc` is `LineRangeClass`
lrc.setBegin(42); // Works
console.log(lrc.begin);