Pesquisa de site

typescript - como tornar os tipos de índice opcionais


Eu quero fazer a declaração de tipo para a seguinte estrutura de dados, na qual a estrutura filha referenciará o pai.

No nível mais interno, ele só possui o tipo Struct, não deve mais ter o tipo Config.

Como os valores do nível vieram da resposta HTTP durante a execução, não posso mais usá-los.

type levels="nível1" | "nível2" | "nível3"

Eu não sei como fazer o tipo Config no mais interno ausente.

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

Erros no código

O tipo '{ name: string; i18n: string; }' não é atribuível ao tipo 'Struct & Config'. O tipo '{ name: string; i18n: string; }' não é atribuível ao tipo 'Config'. A propriedade 'name' é incompatível com a assinatura de índice. O tipo 'string' não é atribuível ao tipo 'Struct & Config'. O tipo 'string' não é atribuível ao tipo 'Struct'.