首页 > 解决方案 > Typescript 构造函数 - 忽略目标上不存在的字段

问题描述

我喜欢在我的类构造函数中使用部分构造函数模式,就像这样..

export class TestClass {
  prop1: string = null;
  prop2: string = null;

  public constructor(init?: Partial<TestClass>) {
    Object.assign(this, init);
  }
}

这对于从例如表单中转储部分对象非常有用。问题是,当我将一个对象传递给该构造函数时,该构造函数具有未在类中定义的字段,无论如何都会添加它们。

const testObj = {prop1= '', prop2 = '', prop3 = 'Don't apply me!'}
const newObj = new TestClass(testObj)

所以这里 newObj 包含 prop3。

有没有办法阻止这种行为,即只添加类中存在的字段?

我看到user4676340提出了类似的问题,并且有以下自定义代码

Object.keys(objectTwo).forEach(key => key in objectOne ? current[key] = objectTwo[key] : null);

有没有一种很好的“TypeScript 方式”来做到这一点,如果没有,我怎么能在构造函数中实现类似上面的东西?

谢谢

标签: angular

解决方案


所以现在我要使用这种似乎有效的方法......如果有人知道更好的方法,请告诉我

        public constructor(init?: any) {
        Object.keys(init).forEach((key) =>
            key in this ? (this[key] = init[key]) : null
        );

推荐阅读