如何解决在接口和/或类中强制执行只读
我正在研究一个用作模型的类,并且我想确保数据是只读的。它本身很简单,但是当数据嵌套时,它似乎变得棘手。让我给出我的代码示例以使其更清楚:
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实例化它时就抛出了错误,因为mymodel.A是未定义的。诀窍是在构造函数之外设置值,这也使我想到了原始问题的解决方案:
export class MyModel {
readonly One: IOne = {
A: "foo",B: "bar"
}
constructor(){}
}
interface IOne {
readonly A: string,readonly B: string
}
在尝试为MyComponent中的mymodel.One.A分配值时,这会产生正确的错误。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。