ts-essentials
ts-essentials copied to clipboard
Suggestion: AddPropRecursively (or as you like)
Hey! I searched a lot but couldn't find this type to use in my project, so I spent some hours learning more advanced typescript and came with this: (Maybe there is a type in this lib that does exactly this, but I really couldn't find / understand the Readme enough)
type AddPropDistributive<Obj extends {}, Prop> =
{ [K in keyof Obj]: (Obj[K] extends {} ? AddPropRecursively<Obj, Prop> : Obj[K]) };
type AddPropRecursively<Obj extends {}, Prop> =
Obj & Prop & AddPropDistributive<Obj, Prop>;
Usage:
You have any type object, let's say
type A = {
B: number,
C: {
D: string
},
E: {
F: {
G: boolean
}
}
type X = AddPropRecursively<A, {_new: number}>
X is = {
_new: number,
B: number,
C: {
_new: number,
D: string
},
E: {
_new: number,
F: {
_new: number,
G: boolean
}
}