1

I want to create a new object only with the properties that i need.

Example:


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' }

i tried with object.assign(objFoo,objDoo), but doens't work. please help

3
  • 1
    You can't do this with typescript, and you also shouldn't use as Foo/Doo because the empty object does not match that interface. Commented Jul 30, 2020 at 20:37
  • nice, and the way to solve this problem is initializing the object properties ? Commented Jul 30, 2020 at 20:39
  • You should just explicitly specify which properties you want to copy, or you keep an array with all properties you want to copy and loop through it. Commented Jul 30, 2020 at 20:40

1 Answer 1

1

If you switch to classes and have very verbose constructors, it can be done. Its not pretty, and I'm not sure I'd recommend it though.

Working stackblitz, see the console log of the objects: 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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.