[英]Typescript - "Link" a child attribute to the same attribute in the parent, so when the parent attribute is updated, it updates the same in the child?
A Company can have a Pia agreement, but doesn't need to have one.公司可以有 Pia 协议,但不一定要有。 So, I have the following.ts classes to demonstrate this.
所以,我有以下 .ts 类来演示这一点。
I just do this let submitObject = new Company();
我只是这样做
let submitObject = new Company();
and then I get a Company object with default null values that I can overwrite based on what's in my form.然后我得到一个公司 object,默认值为 null,我可以根据我的表单中的内容覆盖这些值。
When I set the "id" in the Company, I want it to also set the child (Pia) 's "companyId" using this same value.当我在公司中设置“id”时,我希望它也使用相同的值设置子 (Pia) 的“companyId”。 Is there a way to make it do this automatically, or do I need to manually do
submitObject.pia.companyId = submitObject.id
after every time I finish setting the values of a new Company object?有没有办法让它自动执行此操作,或者我是否需要在每次完成新公司 object 的值设置后手动执行
submitObject.pia.companyId = submitObject.id
submitObject.id?
Company.ts公司.ts
import { Pia } from "./Pia";
export class Company {
id: number = null;
name: string = null;
address: string = null;
authRequired: boolean = false;
piaRequired: boolean = false;
pia: Pia = new Pia;
}
Pia.ts皮亚茨
export class Pia {
companyId: number = null;
agreementNumber: string = null;
effectiveDate: string = null;
expirationDate: string = null;
}
What I've tried:我试过的:
Using extends
/ inheritance (I'm pretty sure I'm doing this incorrectly)使用
extends
/ inheritance (我很确定我做错了)
Company.ts公司.ts
import { Pia } from "./Pia";
export class Company {
constructor(public companyId: number) {
this.id = companyId;
}
id: number = null;
name: string = null;
address: string = null;
authRequired: boolean = false;
piaRequired: boolean = false;
pia: Pia = new Pia(this.companyId);
}
Pia.ts皮亚茨
import { Company } from "./Company";
export class Pia extends Company {
// constructor(companyId: number) {
// super(companyId);
// }
// companyId: number = super.id;
companyId: number = null;
agreementNumber: string = null;
effectiveDate: string = null;
expirationDate: string = null;
}
You may use a getter/setter , although this may get out of hand if you have more properties you want to 'link':您可以使用getter/setter ,尽管如果您有更多想要“链接”的属性,这可能会失控:
class Pia { companyId; constructor(id) { this.companyId = id } } class Company { pia; constructor(pia) { this.pia = pia } get id() { return this.pia.companyId } set id(id) { this.pia.companyId = id } } const c = new Company(new Pia(42)); // c.id += 27 // also works c.id = c.id + 27; // 'linked', inner object was also updated console.log(c.pia.companyId);
Note that it's not really 'linked', it's just that the Company's id
member acts as a proxy between outside code and the inner Pia object's companyId
.请注意,它并不是真正的“链接”,只是公司的
id
成员充当外部代码和内部 Pia 对象的companyId
之间的代理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.