Tips on declaring an object with a nested array of objects in TypeScript

In my code, I have defined two classes. One is called Stuff and the other is called Thing.

class Stuff {
  constructor() { }
  things: Thing[] = [];
  name: string;
}

class Thing {
  constructor() { }
  active: boolean;
}

As I was working on my application, I attempted to declare a field using the following syntax.

blopp: Stuff[] = [
  {name: "aa", things: null}, 
  {name: "bb", things: null}];

Initially, this method worked perfectly fine. However, when I tried to assign an array of things instead of null, I encountered an error stating that it's not assignable to the specified type.

blopp: Stuff[] = [
  {name: "aa", things: [{active: true}, {active: false}]}, 
  {name: "bb", things: null}];

Answer №1

One way to instantiate your objects is by using the new keyword:

class Items {
    constructor(public title: string, public info: Info[] = []) { }
}

class Info {
    constructor(public active: boolean) {

    };
}

var dataList: Items[] = [
    new Items("example A", [new Info(true), new Info(false)]),
    new Items("example B", null)
];

Alternatively, you can utilize interfaces:

interface IInfo {
    active: boolean
}

interface IItems {
    title: string;
    info: IInfo[]
}

var dataList: IItems[] = [
    { title: "example A", info: [{ active: true }, { active: false }] },
    { title: "example B", info: null }];

It is crucial to decide whether classes or interfaces are more suitable for your needs, as some functionalities may not be compatible with anonymous objects:

/*
class Items {
constructor(public title: string, public info: Info[] = []) { }
}
class Info {
constructor(public active: boolean) {

};
}
var dataList: Items[] = [
{ title: "example A", info: [{ active: true }, { active: false }] },
new Items("example B", null)
];
console.log("Is dataList[0] Items:", dataList[0] instanceof Items);
console.log("Is dataList[1] Items:", dataList[1] instanceof Items);

*/
var Items = (function () {
    function Items(title, info) {
        if (info === void 0) { info = []; }
        this.title = title;
        this.info = info;
    }
    return Items;
}());
var Info = (function () {
    function Info(active) {
        this.active = active;
    }
    ;
    return Info;
}());
var dataList = [
    { title: "example A", info: [{ active: true }, { active: false }] },
    new Items("example B", null)
];
console.log("Is dataList[0] Items:", dataList[0] instanceof Items);
console.log("Is dataList[1] Items:", dataList[1] instanceof Items);

Answer №2

Consider utilizing <> or the as keyword for casting:

blopp: Stuff[] = [
  {name: "aa", things: [{active: true} as Thing , {active: false}as Thing]}, 
  {name: "bb", things: null}];
}

Alternatively, you can also use

blopp: Stuff[] = [
  {name: "aa", things: [<Thing>{active: true}  , <Thing>{active: false}]}, 
  {name: "bb", things: null}];
}

Answer №3

Building upon the correct response provided earlier, if you wish to utilize interfaces, you have the option to define nested interfaces within interfaces as demonstrated below:

interface IDevice {
  brand: string
  model: string
}

interface ISmartHome {
  location: string
  devices: IDevice[]
}

interface IHouse {
  smartHomes: ISmartHome[]
}

If you prefer not to assign names to nested parts' types, you can arrange the interface declarations in a nested manner like this:

interface IHouse {
  rooms: {
    name: string
    devices: {
      brand: string
      model: string
    }[]
  }[]
}

Both of these approaches to defining the IHouse interface will provide strict typing for a house structure example, such as the one shown below:

let house: IHouse = {
  rooms: [
    {
      name: "living room",
      devices: [
        { 
          brand: "Samsung",
          model: "TV123"
        },
        { 
          brand: "Apple",
          model: "iPhoneX"
        }
      ]
    },
    {
      name: "bedroom",
      devices: []
    }
  ]
}

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

What are the best ways to transfer information between functional components in a React application?

When working with React, data exchange between class-based components can be done using states and props in the following way: App.js import Name from './Name'; import React, { Component } from 'react' export class App extends Compo ...

What factors does mongo consider when serializing an object?

I recently started working with BigNumbers from the bignumber.js package As I delve into Mongo, I find myself pondering how Mongo manages to serialize objects correctly, such as the BigNumbers. In my case, I have encountered a puzzling situation where two ...

Acquire JSON data structures using Node.js

I've been struggling to find a solution using just keywords - endless scrolling, yet all I can find are tutorials on getting data from JSON structure, rather than getting data structure from JSON. If you're unsure what my end goal is, here are s ...

Steps for displaying or hiding the mobile menu when clicked

I am struggling with displaying a menu and its mobile version in HTML. The mobile menu doesn't seem to be functioning properly. Is there a way to initially show only the menu SVG icon, hide the mobile menu, and then reveal the mobile menu along with t ...

Using form.submit() alongside preventDefault() will not yield the desired outcome

My login form needs to either close the lightbox or update the error box based on the success of the login attempt. I suspect the issue lies with the onclick="formhash(this.form, this.form.password);" which is a JavaScript function that hashes a passwor ...

Looking for a way to extract Regular Expressions from an IgGrid cell in Infragistics?

Is it possible to apply a regular expression to a igTextEditor within an igGrid Updating? I attempted to utilize the validate option, but it was unsuccessful. $("#schedulerTable").igGrid({ columns: $scope.schedulerColumns, widt ...

Struggling to spot my error (codewars, javascript, level 8)

Can You Translate?! After receiving a message on WhatsApp from an unfamiliar number, you wonder if it's from the person with a foreign accent you met last night. Your task is to write a simple function that checks for various translations of the word ...

Original selection unavailable in pagination

I'm encountering an issue on my website where Bootstrap and JQuery don't seem to work well together. $("ul.pagination li:not(.active) a").on("click",function(){ $(".pagination li.active").removeClass("active"); $(this).parent().addClass("activ ...

Retrieve all elements from an array that have the highest frequency of occurrence

Consider an array like [1,4,3,1,6,5,1,4,4]. The element with the highest frequency in this array is 3. The goal is to select all elements from the array that have a frequency of 3, so in this case we would select [1,4]. To achieve this, one possible meth ...

Transmit information from a comprehensive form using AJAX technology

I created a complex form with 30 fields, out of which 3 fields are repeated 10 times. Here's the code: <form id="artikelform" method="POST" name="controleartikelen" action=""> <table id="controle"> <tr><th>Maakartikel</ ...

Preventing distortion of the object when using camera.lookat() in three.js

I have created a piece of code that moves an object randomly on the screen using camera.lookat(). However, I noticed that when the object moves to the sides of the screen, it slightly changes its shape to look at the camera, causing a skewing effect. I wa ...

What causes the canLoad function to create an endless loop when rerouting?

Utilizing Angular's canLoad function in my AuthGuard to authenticate a lazy loaded module at the root of my application. If the user is not authenticated, the module will not load and the user will be directed to the login page. This process works sm ...

Extend jQuery deeply, only replacing values and not adding new keys

For instance, consider the following two JSON objects: First Object: { "surname" : "Raghuvanshi", "work" : { "title": "title1" }, "name" : "Navin" } Second Object: { "work" : { "title": "title2", "field": "field2" }, "name" ...

What is the best way to use the Object3D.lookAt() function to align an ExtrudeGeometry face with an object?

I'm trying to create a 3D Polygon that can face another Object, but I'm struggling to figure out how to do it. I was thinking of using ExtrudeGeometry, but I'm not sure how to apply the Object3D.lookat() function to it. Any suggestions would ...

Is Angular 6 with typescript the golden recipe for layout design?

I've been utilizing the golden layout in conjunction with Angular 6, following the steps outlined in this particular guide. The issue arises when I try to execute GoldenLayoutModule.forRoot(config) The error message states that 'config' ...

Incorporate additional query parameters into a dynamic route with React Router to enhance functionality

I am currently working on incorporating an optional query parameter to the end of a path in order to create URLs like this: "/user/1/cars?makeYear=2020" or "/user/1/cars". The relevant Route is defined as shown below. I have been having ...

gist-react: containing gist within a scrollable div

Struggling to contain a gist within a div with scrollbars on my next.js site using gist-react. It seems like my CSS is being overridden when the gist loads from the underlying dependency. Is there a way to achieve this without modifying the dependency itse ...

Troubleshooting React Native's ScrollView issue with row direction and flexWrap not allowing scrolling

One issue I'm facing in my React Native app is with a ScrollView that contains a list of items wrapped in rows (flexDirection:'row', flexWrap:'wrap'). For some reason, the ScrollView is not scrolling properly... Here is the code f ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...