angular - TypeScript:复制具有匹配属性的对象
问题描述
我只想用我需要的属性创建一个新对象。
例子:
interface Foo {
a: string;
c: string;
}
interface Doo {
a: string;
h: number;
c: string;
}
const objFoo = {} as Foo;
const objDoo = {} as Doo;
objFoo = {}
objDoo = { a: 'hi', h: 1, c: 'gray' }
objFoo = objDoo // only with the properties that matches with properties of objFoo
//output expected
objFoo { a: 'hi', c: 'gray' }
我尝试使用 object.assign(objFoo,objDoo),但不起作用。请帮忙
解决方案
如果您切换到类并且有非常冗长的构造函数,则可以完成。它不漂亮,但我不确定我是否会推荐它。
工作 stackblitz,查看对象的控制台日志:https ://stackblitz.com/edit/angular-vqs81k
export class Foo {
a: string;
c: string;
constructor(kwargs?: Partial<Foo>) {
if (kwargs) {
this.a = kwargs.a;
this.c = kwargs.c;
}
}
}
export class Doo {
a: string;
h: number;
c: string;
constructor(kwargs?: Partial<Doo>) {
if (kwargs) {
this.a = kwargs.a;
this.h = kwargs.h;
this.c = kwargs.c;
}
}
}
let objDoo = new Doo({ a: 'hi', h: 1, c: 'gray' });
let objFoo = new Foo(objDoo);
console.log(objDoo);
console.log(objFoo);
推荐阅读
- python - 通常无法在 Pycharm 上安装 pygame 和软件包
- tensorflow - FCN中Conv2DTranspose层的问题
- quicksort - APL中快速排序的解释
- r - 官员 r 包用于创建具有并排内容的幻灯片 - 内容仅出现在一个部分中
- android - 使用 android EncryptedSharedPreference 的最低 API 级别?
- uikit - 使自定义 SwiftUI 视图适应内置修饰符
- java - 密码和用户名存储在 Apache Ignite 中的什么位置?
- c# - HTMLAgilityPack InnerHTML,解析错误错误
- flutter - 如何解决 OS 错误:Permission denied, errno = 13 in flutter
- java - 在同一个项目中跨多个模块重用测试类