DEV Community

Discussion on: Typescript Partial<T>, where have you been my whole life?

Collapse
 
cookavich profile image
Paul Cook

I do the same except with Object.assign with partials like so:

export class User {
    id: number;
    name: string;
    profile = new Profile();

    constructor(options?: Partial<User>) {
        Object.assign(this, options);
    }
}
Enter fullscreen mode Exit fullscreen mode

Works really nicely for creating and updating data.

onChangeUser(event: FormChangeEvent<UserForm>): void {
    this.user = new UpsertUser({
        ...this.user,
        ...event.value,
        profile: new Profile({
            ...this.user.profile,
            ...event.value.profile
        })
    });
}
Enter fullscreen mode Exit fullscreen mode

Rather than having a web of Object.assign everywhere you actually see and work with the shape of your data.