Home > Software design >  Typescript Nested Object Structure Conditional/Recursion Type
Typescript Nested Object Structure Conditional/Recursion Type

Time:04-21

I have the following type:

type Config = {
  key: string,
  label?: string,
  value?: any,
}

I want to be able to parse through a deeply nested object of these "Config's". Something like this:

  feature1: {
    field1: {
      key: `field1`,
    },
    field2: {
      key: `field2`,
    },
  },

  feature2: {
    group1: {
      field: {
        key: `group1_field`,
      },
    },
    group2: {
      field: {
        key: `group2_field`,
      },
    },
  },

  feature3: {
    group1: {
      subgroup1: {
        field: {
          key: `group1_subgroup1_field`,
        },
      },
      subgroup2: {
        field: {
          key: `group1_subgroup2_field`,
        },
      },
    },
  },

The config's can appear at any depth in the object.

How would I go about writing up a Typescript Type to handle this structure?

I've been playing around with this code thus far:

type Config = {
  key: string,
  label?: string,
  value?: any,
}

type ConfigMapping = {
  [key: string]: Config
}

export type NestedConfig<T> = T extends Config ? Config : {
  [K in keyof T]:
  T[K] extends (infer U)[] ? NestedConfig<U>[] :
  NestedConfig<T[K]>;
}

This is not yet working the way I want. I'm a bit unclear how to create this nested Type.

CodePudding user response:

Since you only want to recursively have constraint for Config node type, We can do it with NConfig type alias -

Code Playground

type Config = {
  key: string,
  label?: string,
  value?: any,
}

type NConfig = Config | Config[] |  { [key: string]: NConfig } 


let x: NConfig = {
   feature1: {
    field1: {
      key: `field1`,
    },
    field2: {
      key: `field2`,
      label: 'hey'
    },
  },

  feature2: {
    group1: {
      field: [{
        key: `group1_field`,
      }],
    },
    group2: {
      field: {
        key: `group2_field`,
      },
    },
  },

  feature3: {
    group1: {
      subgroup1: {
        field: {
          key: `group1_subgroup1_field`,
        },
      },
      subgroup2: {
        field: {
          key: `group1_subgroup2_field`,
        },
      },
    },
  },
}

  • Related