title: How to add a property to every sub-object of a nested object in Typescript?
body: <p>I am trying to type a function <code>addId</code> that inputs an object and returns the same object but adds a property <code>_id: string</code> to every sub-object.</p>
  <p>Say for example that the input is an object constructed from the following class.</p>
  <pre><code>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()
  </code></pre>
  <p>In this case <code>addId(a)</code> would return</p>
  <pre><code>A {
    _id: 'id1'
    a: 1
    b: { bb: 2, _id: 'id2' }
    c: [1,2,3]
  }
  </code></pre>
  <p>The parameter to <code>addId</code> can be an object of any class, not specifically the class <code>A</code>. The parameter can be built up recursively from json, objects, and arrays and can have an arbitrary nesting depth.</p>
  <p>I am not looking for an implementation of <code>addId</code>, just the return type. I think the solutions would use similar techniques to the ones used for the type for <code>DeepReadonly&lt;T&gt;</code> defined here: <a href="https://github.com/piotrwitek/utility-types/blob/master/src/mapped-types.ts" rel="nofollow noreferrer">https://github.com/piotrwitek/utility-types/blob/master/src/mapped-types.ts</a></p>