Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

201
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda