I have created a base class that contains various properties:
class Component {
readonly id: number
readonly type: number
}
Now, I am looking to create some subclasses, such as:
class HealthComponent extends Component {
max_health: number,
current_health: number
}
etc.
My goal is for HealthComponent
to exhibit the same behavior as an Immutable.Record
:
const health = HealthComponent(100, 100);
health.max_health = 40; // This should not work
const new_health = new HealthComponent(40, health.current_health); // This works
All of these classes are strictly data-oriented with no behavioral methods. To ensure immutability, I want to prevent modifications and instead return a new object or throw an error similar to how it's done in Immutable.js. However, I am struggling to find the best approach to achieve this.
The approach I'm currently considering involves giving each subclass a readonly data
property that is an Immutable.Record
containing the relevant fields. Yet, even this solution falls short since modifying it would only result in a new data
object rather than an entirely new Component
object. Moreover, this method does not guarantee consistency across all subclasses.
Another option under consideration is making the base class an Immutable.Record
with a data: Immutable.Map
field, while requiring subclasses to provide an Immutable.Map
to the super
constructor with all necessary keys. Unfortunately, this setup leaves room for unrestricted addition of new keys.
Are there any design patterns available that could assist me in achieving my intended functionality?