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

125
Vistas
Type checking is not happening for nested object

I am working on an Angular application. In that I have an interface IAbc:

interface IAbc {
    id: number,
    name: string
}

And another interface IXyz which uses the above interface like below:

interface IXyz {
    id: number,
    value: string | number | Date | IAbc[];
}

Here, the value can be of any type of data, so I have narrowed down on the types.

I have created a new variable:

let someVar: IXyz;

someVar = {
    id: 100,
    value: [
        {
            id: 1,
            name: 'abc'
        },
        {
            id: 2,
            name: 'xyz'
        }
    ]
};

Since the value can be a list also, I have to use forEach on it to do some operation:

someVar.value.forEach((x: IAbc) => console.log('some operation on value, ', x))

But, I get this error on forEach:

Property 'forEach' does not exist on type 'string | number | Date | IAbc[]'.
  Property 'forEach' does not exist on type 'string'.(2339)

I think logically this should work. Is there something wrong with the typescript?

I have created a playground link, where I have reproduced this.

Let me know your thoughts. Thanks!


P.S.: I know I can use any over there and it will work smoothly, but the usage of any has been disabled by the linting of the application.

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

To get rid of the error you can use a typeguard.

function isArray(value: string | number | Date | IAbc[]): value is IAbc[] {
  return (value as IAbc[]).forEach !== undefined;
}

if( isArray(someVar.value) ) {
    someVar.value.forEach((x: IAbc) => console.log('some operation on value, ', x))
}

You can see it working in an updated version of your playground here

about 4 years ago · Santiago Trujillo Denunciar

0

You need a typecast to tell the compiler this is indeed an array

(someVar.value as IAbc[]).forEach((x: IAbc) => console.log('some operation on value, ', x))
about 4 years ago · Santiago Trujillo 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