Typescript-根据其他类实例创建一个新的类实例

时间:2018-11-15 15:18:23

标签: typescript

说我有这两节课:

class MyTypeOne {
  constructor(
      public one = '',
      public two = '') {}
}

class MyTypeTwo extends MyTypeOne {
  constructor(
      one = '',
      two = '',
      public three = '') {
    super(one, two)
  }
}

基于现有MyTypeTwo实例创建MyTypeOne实例的最简洁方法是什么?

1 个答案:

答案 0 :(得分:0)

除非您要从字面上抓住对象键并进行循环,否则映射将发生在某个地方,这实际上将更难阅读并且需要更多行代码...因此,我可能只使用一些创造性的模式!

class MyTypeOne {
    constructor(
        public one = '',
        public two = '') { }
}

class MyTypeTwo extends MyTypeOne {
    constructor(
        one = '',
        two = '',
        public three = '') {
        super(one, two)
    }

    static fromMyTypeOne(myTypeOne: MyTypeOne) {
        return new MyTypeTwo(myTypeOne.one, myTypeOne.two);
    }
}

const one = new MyTypeOne('a', 'b');
const two = MyTypeTwo.fromMyTypeOne(one);

console.log(two);

自动映射

为完整起见,这是自动映射成员的长版本。这是一组不同的权衡方法!

class MyTypeOne {
    constructor(
        public one = '',
        public two = '') { }
}

class MyTypeTwo extends MyTypeOne {
    constructor(
        one = '',
        two = '',
        public three = '') {
        super(one, two)
    }

    static fromMyTypeOne(myTypeOne: MyTypeOne) {
        const typeTwo = new MyTypeTwo();

        for (let key in myTypeOne) {
            if (myTypeOne.hasOwnProperty(key)) {
                typeTwo[key] = myTypeOne[key];
            }
        }

        return typeTwo;
    }
}

const one = new MyTypeOne('a', 'b');
const two = MyTypeTwo.fromMyTypeOne(one);

console.log(two);