Typescript:如何将对象转换或分配给具有较少属性的类型?(从大到小)

dmd*_*dmd 6 typescript

我有三个对象(类),它们如下所示:

class A {

  public value1: string;
  public value2: string;
  public value3: string;
  public value4: string;
  public value5: string;

}

class B {

  public value1: string;
  public value2: string;

}

class C {

  public value3: string;
  public value4: string;
  public value5: string;

}
Run Code Online (Sandbox Code Playgroud)

现在我有一个 JSON,如下所示:

{
  "value1": "ONE",
  "value2": "TWO",
  "value3": "THREE",
  "value4": "FOUR",
  "value5": "FIVE"
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有任何干净的方法可以将类转换A为类B和类C

我尝试了这种方法,但是在 后map,类B具有 中的所有 5 个属性,A而不是 中定义的 2 个属性B

class B {

  public value1: string;
  public value2: string;

  constructor(item: A) {
    Object.assign(this, item);
  }

}


let arr1: A[{"value1":"ONE","value2":"TWO","value3":"THREE","value4":"FOUR","value5":"FIVE"}];
let arr2 = arr1.map(item => new B(item));
Run Code Online (Sandbox Code Playgroud)
Result: B -> {"value1":"ONE","value2":"TWO","value3":"THREE","value4":"FOUR","value5":"FIVE"}]
instead of 
B -> {"value1":"ONE","value2":"TWO"}]
Run Code Online (Sandbox Code Playgroud)

Med*_*uly 1

您要求 Typescript 修改值
Typescript 不会运行您的代码,仅编译和检查类型安全

你可以做的是:为 B 类定义 null 属性,并检查键

class A {
  public value1: string
  public value2: string
  public value3: string
  public value4: string
  public value5: string
}
class B {
  public value1: string = undefined // <-- define
  public value2: string = undefined // <-- define
  constructor (item: A) {
    const keys = Object.keys(item) // get items keys
    const thisKeys = Object.keys(this) // get this class keys
    const limitedItem = keys.reduce((newObj, key) => { // combine same keys
      if (thisKeys.includes(key)) {
        newObj[key] = item[key]
      }
      return newObj
    }, {})
    Object.assign(this, limitedItem) // asign to this class
  }
}

const arr1 = [{ value1: '1', value2: '2', value3: '3', value4: '4', value5: '5' }]
let arr2 = arr1.map(item => new B(item))
console.log('arr2', arr2)

// arr2 [ B { value1: '1', value2: '2' } ]
Run Code Online (Sandbox Code Playgroud)