Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
TypeScript defining recursive object with known end?

first time posting a question.

So my problem is that I want to define an object for storing strings in different languages. This needs to be flexible so the best I've come up with is a nested object structure, but I want the last object to be a specific type or interface.

At first I tried:

interface Text {
  [key: string | number]: ComponentText | Language;
}

interface Language {
  [key: string]: string;
}

text: Text = {
  title: {
    en: "English text",
    sv: "Swedish text",
    fr: "French Text",
    es: "Spanish Text",
  }
  paragraph: {
    subText: {
      en: "English text",
      sv: "Swedish text",
      fr: "French Text",
      es: "Spanish Text",
    }
  }
}

// getCurrLang(s: any) handles getting the correct language string or throws an error when "s" isn't "Language".

But I'm getting errors when I try to retreive the getCurrLang(text['paragraph']['subText']) saying:

Argument of type 'string | Text | Language' is not assignable to parameter of type 'Text | Language'. Type 'string' is not assignable to type 'Text | Language'.

This is something I've come up with that I thought would solve the problem, but unless the key value can contain the same as "language" this doesn't work and solves nothing:

type LangCode = 'en' | 'sv' | 'fr' | 'es';

interface Text {
  [key: string]: ComponentText | Array<ComponentText>;
  language?: Language;
}

type Language = {
  [key in LangCode]: string;
};

Is there a way to define this type of structure or something better?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda