I am currently working on a class that acts as a Model and I want to ensure that the data within it is read-only. While this may seem straightforward at first, things get more complicated when dealing with nested data structures. Let me provide an example from my code to illustrate this further:
export class MyModel {
readonly One: IOne;
readonly Two: ITwo;
readonly Three: IThree;
constructor() {
this.One.A = "foo";
this.One.B = "bar";
this.Two.C = "totally";
this.Two.D = "utterly";
this.Three.E = "completely";
this.Three.F = "messed up"
}
}
interface IOne {
A: string;
B: string;
}
interface ITwo {
C: string;
D: string;
}
interface IThree {
E: string;
F: string;
}
Now, in a component:
import { MyModel } from './my.model';
export MyComponent {
dataB:string;
dataD:string;
dataE:string;
constructor(
private mymodel: MyModel
){
this.dataB = mymodel.One.B; // works as expected
mymodel.Two = ""; // causes error due to readonly property, which is expected
mymodel.Three.F = "something else"; // works, but I also want this to be read-only
}
}
The goal here is to organize data where it belongs while benefiting from IDE suggestions like auto-completion when typing 'mymodel.One.B'. However, I also need the properties from the Interfaces to be read-only.
If I mark the Interfaces as readonly, I naturally encounter errors in MyModel since I cannot assign values to read-only properties. To work around this, I attempted to create classes implementing these Interfaces with readonly properties and then use those classes instead of the interfaces. This approach did not prevent assigning values in MyComponent though. Here's an example:
export class MyModel {
readonly One: One;
readonly Two: Two;
readonly Three: Three;
constructor() {}
}
class One implements IOne {
readonly A = "foo";
readonly B = "bar";
}
class Two implements ITwo {
readonly C = "totally";
readonly D = "utterly";
}
class Three implements IThree {
readonly E = "completely";
readonly F = "messed up";
}
interface IOne {
A: string;
B: string;
}
interface ITwo {
C: string;
D: string;
}
interface IThree {
E: string;
F: string;
}
Despite these changes, the outcome remains the same in MyComponent. How can I enforce read-only for properties A, B, C, etc.?