Christer Carlsund Christer Carlsund - 4 years ago 241
TypeScript Question

Recursive Partial<T> in TypeScript 2.1

I have this interface:

export interface UserSettings
{
one: {
three: number;
four: number;
};
two: {
five: number;
six: number;
};
}


...and want to turn it into this:

export interface UserSettingsForUpdate
{
one?: {
three?: number;
four?: number;
};
two?: {
five?: number;
six?: number;
};
}


...but
Partial<UserSettings>
produces this:

{
one?: {
three: number;
four: number;
};
two?: {
five: number;
six: number;
};
}


Is it possible to use mapped types to make all the properties on all depths optional, or do I have to create an interface manually for that?

Answer Source

you could make your own mapping type, like this:

type RecursivePartial<T> = {
    [P in keyof T]?: RecursivePartial<T[P]>;
};

enter image description here

Unfortunately, this does not work for array-typed fields. There does not seem to be a way to do conditional type mapping yet either; i.e. limit to primitives. See https://github.com/Microsoft/TypeScript/pull/12114#issuecomment-259776847

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download