DEV Community

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

Collapse
 
emptyother profile image
emptyother

I normally use Partial<T> interface when making class constructors.

class MyClass {
    myProp = 0; // Default values are applied first.
    constructor(cfg: Partial<MyClass> = {}) {
        extend(this, cfg); // Method that shallow-copies properties from cfg to this, overwriting any defaults.
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nickraphael profile image
Nick Raphael

Interesting pattern. I may have to play with it. Thanks!

Collapse
 
daniel15 profile image
Daniel Lo Nigro

Your extend method just looks like Object.assign :)

Collapse
 
emptyother profile image
emptyother • Edited

Completely forgot that one exists. Symptom of working too much with an old IE11-supported javascript framework. :P

Thread Thread
 
nombrekeff profile image
Keff • Edited

Nice, I didn't know about Partial, nice find, will be useful!

Yup it could be used, but take into account that Object.assign doesn't merge nested objects.

let objA = { b: { name: 'Train' } };
let objB = { b: { description: 'A vehicle that does not like to go uphill :)' } };

let merged = Object.assign(objA, objB);
> { b: { description: "A vehicle that does not like to go uphill :)" } }


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.