DEV Community

Suguru Inatomi
Suguru Inatomi

Posted on

4

Merging objects with Partial type

My usual implementation pattern of immutable merging in TypeScript.

class MyClass {
    constructor(public id: string, public name: string) {}

    clone() {
        return new MyClass(this.id, this.name);
    }

    merge(another: Partial<MyClass>) {
        return Object.assign(this.clone(), another);
    }
}

const objA = new MyClass("1", "foo");

const objB = objA.merge({ name: "bar" });

console.log(objA !== objB);
console.log(objB.id === "1");
console.log(objB.name === "bar");
Enter fullscreen mode Exit fullscreen mode

Partial<MyClass> allows us to pass an object matching MyClass partially.

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay