在接口和/或类中强制执行只读



我正在处理一个用作Model的类,我想确保数据是只读的。它本身就足够简单,但当数据嵌套时,它似乎会变得棘手。让我举一个我的代码示例来更清楚地说明这一点:

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;
}

然后在一个组件中:

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 = ""; // gives error since it is readonly, as expected
mymodel.Three.F = "something else"; // works, but I want this to be readonly as well
}
}

这个想法是,我可以将数据保存在最有意义的地方,但也允许我的IDE在键入mymodel时提示可用的内容。One.B。但是,我需要使接口中的属性(不确定我在这里使用的术语是否正确(也是只读的。

如果我向接口添加只读,我当然会在MyModel中出错,因为我无法设置只读的值。为了解决这个问题,我尝试创建其他实现这些接口的类,在类中设置只读,然后使用这些类而不是接口,这并没有给出错误,但仍然没有阻止它们在MyComponent中赋值。示例:

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;
}

MyComponent中的结果是相同的。如何对A、B、C等强制只读。?

我找到了实现这一目标的正确方法。

我没有意识到这一点,但我编写MyModel的方式在MyComponent实例化它的那一刻就抛出了一个错误,因为我的模型。A未定义。诀窍是在构造函数之外设置值,这也让我找到了最初问题的解决方案:

export class MyModel {
readonly One: IOne = {
A: "foo",
B: "bar"
}
constructor(){}
}
interface IOne {
readonly A: string,
readonly B: string
}

这在尝试为mymodel赋值时产生了正确的错误。MyComponent中的一个.A。

最新更新