how to make index types optional

Viewed 78

I want to make type declaration for the following data structure, in which child structure will reference parent.

In the innermost level, it only has the Struct type, must not hava the Config type anymore.

As level values came from http response during runtime, I can't use it any more.

type levels = "level1" | "level2" | "level3"

I don't know how to make the Config type in the innermost absent.


interface Struct {
  name: string
  i18n: string
}

type  Config = {
  // [level in levels ]: Struct & Config
  [level: string]: Struct & Config
}

const x: Struct & Config = {
  name: "one",
  i18n: "1",
  level1: {
    name: "two",
    i18n: "2",
    level2: {
      name: "three",
      i18n: "3",
      level3: {
        name: "four",
        i18n: "4"
      }
    }
  }
}

Errors in code

Type '{ name: string; i18n: string; }' is not assignable to type 'Struct & Config'. Type '{ name: string; i18n: string; }' is not assignable to type 'Config'. Property 'name' is incompatible with index signature. Type 'string' is not assignable to type 'Struct & Config'. Type 'string' is not assignable to type 'Struct'.

0 Answers
Related