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

238
Visualizações
TypeScript - using recursive generics properly

I am trying to use recursive generics in a way I can get a lot of help from editor.

Here is an example:

interface ServiceEndpointNode {
  self: string;
  context?: Record<string, ServiceEndpointNode>
}

const ServiceEndpoints: ServiceEndpointNode = {
  self: 'BASE_URL',
  context: {
    songs: {
      self: 'GET_SONGS',
      context: {
        getSong: {
          self: 'GET_SONG',
        },
        getContributors: {
          self: 'GET_CONTRIBUTORS',
        }
      }
    }
  }
}

This works properly and the structure is strict, but I don't got help from the editor. For example I want help like:

ServiceEndpoints.context.songs.context.getsong.self

But because I only told the typing that the context should be a string I don't really receiving help about the traversable object. I guess I need to be include some generics or something, but don't know how to achieve that. :(

So I want to have to maintain this strict structure, yet get help from the editor for all the possible routes, keys, etc.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Now you can use Optional chaining in TypeScript simplify as shown below. So that typescript compiler will expect NULL | underfined

    console.log(ServiceEndpoints.context?.songs.context?.getSong?.self);
    // OUTPUT: "GET_SONG" 
about 4 years ago · Juan Pablo Isaza Relatório
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