Typescript -将子属性“链接”到父属性中的相同属性,因此当父属性更新时,它也会更新子属性中的相同属性?

rsaldnfx  于 2023-01-27  发布在  TypeScript
关注(0)|答案(1)|浏览(159)

一个公司可以有一个Pia协议,但并不需要有一个。所以,我有下面的. ts类来演示这一点。
我只需要执行let submitObject = new Company();,然后得到一个Company对象,它具有默认的空值,我可以根据表单中的内容覆盖这些空值。

    • 当我在Company中设置"id"时,我希望它也使用相同的值设置子对象(Pia)的"companyId"。**是否有方法使它自动执行此操作,或者是否需要在每次设置完新Company对象的值后手动执行submitObject.pia.companyId = submitObject.id

Company.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;
}
    • 我所尝试的**

使用extends/inheritance(我很确定我做错了)
Company.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;
}
qvk1mo1f

qvk1mo1f1#

您可以使用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);

注意,它不是真正的“链接”,只是Company的id成员充当外部代码和内部Pia对象的companyId之间的代理。

相关问题