首页 > 解决方案 > 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),但不起作用。请帮忙

标签: angulartypescript

解决方案


如果您切换到类并且有非常冗长的构造函数,则可以完成。它不漂亮,但我不确定我是否会推荐它。

工作 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);


推荐阅读