In TypeScript, while in a class, is there an elegant way to set a value only once? In other words, is there an equivalent of setting a value as readonly
after giving it a value?
For example:
class FooExample {
public fixedValue: string;
public setFixedValue(value: string): void {
if (!this.fixedValue) {
// this value should be immutable
this.fixedValue = value;
}
}
}
I am not looking for a getter, because the class property could be changed within the class itself.
After reading the suggested answers and doing my own research I believe I have found the most elegant solution. You first define the value as an Object
and then freeze()
the Object
after populating the related property.
class FooExample {
public fixedValue = {
value: '';
};
public setFixedValue(value: string): void {
if (!Object.isFrozen(this.fixedValue)) {
this.fixedValue.value = value;
Object.freeze(this.fixedValue);
}
}
}