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

198
Visualizações
How to type an object that references to itself but also allows other values?

I want to type the following nested object. the type works when you assign it to an object, but is there a way to make it work while accessing its properties?

type NestedObject = {
   [key: string]: NestedObject | string;
}

const obj: NestedObject = {
  a: '123',
  b: {
    b_a: {
      b_a_a: '456'
    },
    b_b: '789'
  }
};

function ABC(myNestedObject: NestedObject) {
    const nestedObject: NestedObject = {
      // Property 'fail' does not exist on type 'string | NestedObject'.
      'failProperty': myNestedObject.properties.fail 
    };
}

I tried to make it conditional by checking whether it extends from string, but I'm having challenges accessing the current value for the specified key. This for instance, doesn't work:

type NestedObject = {
  [K in NestedObject]: NestedObject[K] extends string ? string : NestedObject;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to narrow down whether the .properties property is a string or a NestedObject. If it's a string, then referencing myNestedObject.properties.fail would result in problems - which is why TypeScript is warning you about it.

Construct the code paths so that if the typeof results in string, you don't reference myNestedObject.properties.fail.

function ABC(myNestedObject: NestedObject) {
    if (typeof myNestedObject.properties === 'string') {
        throw new Error();
    }
    const nestedObject: NestedObject = {
      // Property 'fail' does not exist on type 'string | NestedObject'.
      'failProperty': myNestedObject.properties.fail 
    };
}
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