简体   繁体   English

继承类型成员实体类型脚本

[英]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 . 在服务器端,我具有用Java编写的相同结构,User person成员可以是FPersonJPerson I want be able to cast it according the person type.. How can I do that in Typescript? 我希望能够根据人员类型进行转换。如何在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? 如何实现isFPerson()方法? And how can I force typescript the store the extra fields present in FPerson and JPerson into a Person variable? 以及如何强制打字稿将FPersonJPerson存在的额外字段存储到Person变量中?

Kind of like in java: 有点像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. 尽管FPersonJPerson需要扩展Person ,但问题代码中并非如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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