0

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
      }
    }
  }
}

1 Answer 1

0
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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks @Dimava. this works appreciated
i am extending this to a generic it kind looses the types. see line 68 - 74 that organization can not be reached. playground

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.