Nested object type checking is not being performed

I have been developing an Angular application and working with two interfaces: IAbc and IXyz.

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

In my code, I initialize a variable someVar: IXyz; with some data.

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

However, when trying to perform an operation using forEach on the nested array in value, I encounter an error:

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

Although logically it should work, I suspect there might be a TypeScript issue. I have created a playground link demonstrating this issue.

I appreciate any insights or suggestions. Thank you!


P.S.: While using any could resolve this, it has been restricted by the linting rules of the application.

Answer №1

To address the error, implementing a typeguard is recommended.

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))
}

To witness the solution in action, check out the updated version of your playground here

Answer №2

To inform the compiler that this is an array, you must use a typecast

(someVar.value as IAbc[]).forEach((x: IAbc) => console.log('performing operation on each value, ', x))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing Firebase credentials securely in Vue.js applications after deployment with environment variables (env_var)

I've been attempting to deploy my firebase&vue application, but I've encountered issues with adding firebase credentials to the environment variables. Here's the structure within vue.js: config ---- key.js ---- keys_dev.js ---- key ...

Unlocking the power of translation in React: Implementing Amazon Translate or Google Translate for AXIOS responses

I'm currently working on converting Axios JSON responses in React. Here is the code snippet: axios.get('https://jsonplaceholder.typicode.com/users') .then(res => { ...translation_logic_here setU ...

Incorporating a Vue application into a server-side framework application, encountering issues with Vue Public Path

Summary - Incorporating a Vue app into a Phoenix app. Constructing the Vue app with vue cli and ensuring the files are placed correctly within the Phoenix project directories. After building, there is an issue where the asset file paths do not align with t ...

The CRUD application in MongoDB is functioning flawlessly within the vscode terminal, however, it is experiencing issues when trying to run it in separate terminals such as cmd

https://i.sstatic.net/OrRmg.png However, when using any independent terminal like Git bash or cmd, it is throwing an error https://i.sstatic.net/1GHxa.png https://i.sstatic.net/TIouh.png GitHub URL I am unsure why this error is occurring. Could you please ...

What could be the reason for the form value object being devoid of any content

I am seeking help to understand how to write a custom validator for a reactive form. Here is the component code: private form: FormGroup; ngOnInit() { const this_ = this; this.form = new FormGroup({ 'email': new FormContr ...

The slice() method in arrays provides a reference to the elements rather than copying

In my file, I am exporting an object in the following manner: export const LINECHART2_DATA = { series: [{ data: [], name: 'HR', }, { etc... }] } The way I import it is like this: import { LINECHART2_DAT ...

What is the best way to utilize a parent variable in child JavaScript code?

This code utilizes inheritance where the child adds something to the scene that is declared in the parent. How can this be achieved without causing an error when trying to access the scene in the child level? function Parent(domElement, renderStatistic ...

Fetching information using JSON for creating a RangeArea Chart with CanvasJS

I'm currently working on creating a range area chart with CanvasJS and PHP to fetch data from a database. After setting up the php script to retrieve values from the DB, here's what I have: <?php header('Content-Type: application/json&a ...

Identify the category of the component

Using a Link component from version 4.0.0-beta.2, I am exploring its capability to override the root element with a field called component. My goal is to wrap the Link component in a new component called MyLink and pass a custom component through props: ...

Consolidating Arrays in MongoDB: A Handy Function

I have a substantial dataset containing documents that sometimes reference each other and sometimes do not. Before I can perform mapreduce operations based on these cross-references, I need to ensure that the array of cross-references is consistent for eve ...

Incorporate an HTML code string into an Angular 2 template

I am working with HTML code stored in a Component variable, shown below: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `Hi <div [innerHTML]="name"></div>`, styleUrls: [' ...

Refresh the child component whenever there is a change in the parent's state

As of now, I am in the process of developing a MultiCheckbox Component which looks like this: Checkbox.tsx import './Checkbox.scss'; import React, {ChangeEvent, Component} from 'react'; /* * Description of Checkbox properties */ in ...

Exploring the variations in module definitions with requireJS

Struggling with requireJS right now. It's an AMD which means it's asynchronous. Typically, a module would be defined like this: define("some Name", ["./moduleOne"], function(moduleOne){ //this would be undefined moduleOne.whatEver(); v ...

What issue could be present in my JavaScript promise setup?

I'm currently working on developing my own Promise in JavaScript to enhance my comprehension of how Promises work. I've encountered a roadblock while trying to understand the .then method and I need some guidance: I came across the documentation ...

What is the process for indicating an option as "chosen" within Embedded JavaScript Templating (EJS)?

I've been working on a function that allows users to modify each other's data, including the ability to change roles. I'm having trouble getting the select form to display the current role of a user with the "selected" attribute. This is wh ...

React Native's NativeBase checkbox component: Overlapping text causing the content to extend beyond the confines of the screen

I am having trouble getting the text inside a checkbox (using nativebase) to shrink. Does anyone know why this is happening? Do I need to add some flex properties? import React from "react" import {Box, Center, Checkbox, Heading, NativeBaseProv ...

How to locate the parent element in a JQuery event

I need to verify whether the target has a specific parent after adding a click event. This is how my code looks: $(document).click(function(event){ // Check here if the target has a specific parent, for example -> #parent }); Is there a way to ach ...

display border around a div when a hyperlink is selected

Can someone help me with showing the top border on a footer when a link is clicked, and hiding it when the same link is clicked again? I've tried using display:none;, but it's affecting the functionality. Any assistance would be greatly appreciat ...

Data is not found in req.body when making a fetch request

I have been attempting to send a fetch request to my server, but I am consistently receiving an empty req.body. Here is the client-side script: const form = document.getElementById('form1') form.addEventListener('submit', (e) => ...

Transferring files from the android_asset directory to the SD Card

I am trying to play video files that are packaged within a Cordova application. My goal is to transfer these files from the android_asset folder to the SD card using the File API in JavaScript. However, I am encountering difficulties in accessing this fol ...