I am trying to type a function addId that inputs an object and returns the same object but adds a property _id: string to every sub-object.
Say for example that the input is an object constructed from the following class.
class A {
a: number
b: { bb: number }
c: number[]
constructor() {
this.a = 1
this.b = { bb: 2 }
this.c = [1,2,3]
}
}
const a = new A()
In this case addId(a) would return
A {
_id: 'id1'
a: 1
b: { bb: 2, _id: 'id2' }
c: [1,2,3]
}
The parameter to addId can be an object of any class, not specifically the class A. The parameter can be built up recursively from json, objects, and arrays and can have an arbitrary nesting depth.
I am not looking for an implementation of addId, just the return type. I think the solutions would use similar techniques to the ones used for the type for DeepReadonly<T> defined here: https://github.com/piotrwitek/utility-types/blob/master/src/mapped-types.ts