简体   繁体   中英

Inherit Type Member Entity Typescript

I have the following data structure:

export abstract class Person {
    ...
}

export class FPerson extends Person {
    a: A;
    b: B;
}

export class JPerson extends Person {
    c: C;
}

export class User {
    person: Person;
}

On server side I have the same structure written with java, the User person member can be either FPerson or JPerson . I want be able to cast it according the person type.. How can I do that in Typescript?

Something like that:

doSomething(u: User) {
    let fp: FPerson;
    let jp: JPerson;

    if (u.person.isFPerson()) {
       fp = <FPerson> u.person;
    } else {
       jp =  <FPerson> u.person;
    }
  ...
}

How can I implement the isFPerson() method? And how can I force typescript the store the extra fields present in FPerson and JPerson into a Person variable?

Kind of like in java:

doSomething(u: User) {
    let fp: FPerson;
    let jp: JPerson;

    if (u.person instanceof FPerson) {
       fp = <FPerson> u.person;
    } else {
       jp = <JPerson> u.person;
    }
  ...
}

Though both FPerson and JPerson need to extend Person , which isn't the case in the code in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM