Home > OS >  Typescript Type Flatten Child nested objects
Typescript Type Flatten Child nested objects

Time:11-17

i have been following this example and here to flatten a type invain. Most of this flatten the object completely into removing the nests. I would like to to maintain my structure, just removing some wrappers (in this case body) in the nested objected which can be anything and n deep.

I would like to transform my type from

type TestInterface {
  id: string
  body: {
    title: string 
    something: string 
    user: {
      id: string
      body: {
        firstname: string
        lastname: string
        age: number
      }
    }
    country: {
      id: string
      body: {
        code: string
        name: string
        region: {
          id: string
          body: {
            code: string
            name: string
            continent: {
              id: string
              body: {
               code: string
               name: string
              }
            }
          }
        }
      }
    }
  }
}

the required output is the same type structure above but with the body wrapper dropped.

type TestInterface {
  id: string
  title: string 
  something: string 
  user: {
    id: string
    firstname: string
    lastname: string
    age: number
  }
  country: {
    id: string
    code: string
    name: string
    region: {
      id: string
      code: string
      name: string
      continent: {
        id: string
        code: string
        name: string
      }
    }
  }
}

CodePudding user response:

type Pure<T> = T extends object ? {[K in keyof T]: T[K]} : T
type Flatten<T> = Pure<
| T extends {body: any} ? Flatten2<Omit<T, 'body'> & T['body']> : Flatten2<T>
>
type Flatten2<T> = T extends object ? {[K in keyof T]: Flatten<T[K]>} : T

type X = Flatten<TestInterface>

Playground

  • Related