angular - 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 方式”来做到这一点,如果没有,我怎么能在构造函数中实现类似上面的东西?
谢谢
解决方案
所以现在我要使用这种似乎有效的方法......如果有人知道更好的方法,请告诉我
public constructor(init?: any) {
Object.keys(init).forEach((key) =>
key in this ? (this[key] = init[key]) : null
);
推荐阅读
- python - 在 Linux 上的重复进程中具有线程的 Python 脚本
- javascript - 无法使用 jQuery 从字符串中删除反斜杠或连字符
- java - 在jsp中将ArrayList转换为Array
- excel - .Interior.ColorIndex 问题
- docker - 在 Docker Compose 中设置 CPU 限制
- mongodb - 一个 pod 中的 Springboot 应用程序无法通过 Openshift 连接到另一个 pod 上的 mongodb
- html - 如何在 HTML/CSS 的列表( ul > li )中对齐图像?
- reactjs - TypeError:fs.readFileSync 不是函数
- ruby-on-rails - 文件未在创建时附加,但在 zendesk 更新时附加
- javascript - 排序算法在找到正确的条件时停止