TS2322: Subclass missing property, yet it still exists

In my project, I have defined two Angular 4 component classes.

The first class, referred to as the superclass:

export class SectionComponent implements OnInit {
  slides: SlideComponent[];

  constructor() {
  }

  ngOnInit() {
  }

}

And then there's the subclass:

export class FrontPageSectionComponent extends SectionComponent implements OnInit {
  slides: SlideComponent[];

  constructor() {
    super();
  }

  ngOnInit() {
    this.slides = [];
  }

}

My goal is to create an array of instances of the superclass in my AppComponent...

export class AppComponent implements OnInit {
  sections: SectionComponent[];

  constructor() {
  }

  ngOnInit(): void {
    this.sections = [
      new FrontPageSectionComponent()
    ];
  }
}

However, when attempting to do so, I encounter an error message:

TS2322: Type 'typeof FrontPageSectionComponent[]' is not assignable to type 'SectionComponent[]'. Type 'typeof FrontPageSectionComponent' is not assignable to type 'SectionComponent'. Property 'slides' is missing in type 'typeof FrontPageSectionComponent'.

I did not explicitly specify any types myself and a search within the codebase did not return any results for 'typeof FrontPageSectionComponent', leading me to believe that this issue stems from TypeScript inference mechanisms.

Answer №1

Your list

data: DataComponent[];

represents a group of DataComponent objects.

If you wish to create a list of classes that inherit from DataComponent, it is indeed possible.

You must use the type of the class property, not the type of its instances.

To determine the type of a value, utilize the typeof keyword.

const d: typeof DataComponent = DataComponent;

Therefore, to define a list of classes that generate instances of DataComponent, you would indicate.

data: Array<typeof DataComponent>;

In a more abstract sense, you can denote

data: Array<new () => DataComponent>;

Such methods are highly beneficial in advanced programming.

Keep in mind that I am using the Array<...> format for better clarity when nesting, [] also functions as well

Answer №2

After inserting new FrontPageComponent() instead of FrontPageComponent into the array, everything started working smoothly.

It then struck me that Angular has a way of automatically creating these instances, so I made some adjustments in my code:

export class AppComponent implements OnInit {
  sections: SectionComponent[];

  constructor(private frontPage: FrontPageSectionComponent) {
  }

  ngOnInit(): void {
    this.sections = [
      this.frontPage,
    ];
  }
}

This change resolved the error. However, if there are better practices to follow, please do share them with me.

In order to maintain separation of concerns and prevent a cluttered constructor, I am planning to move the sections to a SectionService. Although I didn't find much information on this while searching online, I decided to document my findings here.

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 is the best approach to creating customizable modules in Angular2?

I'm exploring the most effective approach to configuring modules in Angular 2. In Angular 1, this was typically achieved through providers. As providers have been altered significantly, what is the preferred method for passing configuration parameters ...

What are the limitations of jest and jsdom in supporting contenteditable features?

I am facing an issue with a particular test case: test('get html element content editable value', () => { // arrange const id = 'foo'; document.body.innerHTML = `<div id='${id}' contenteditable="true">1</div ...

The directive does not function properly when used across multiple files

Struggling with @Directives and @Hostlisteners - seeking assistance The directive added to the input seems unresponsive, failing to trigger any events or console.log(). I'm puzzled and frustrated as there appears to be a missing piece of the puzzle t ...

Angular2 - Transmitting validation information from parent component to child component input validation

I am currently developing an automatic word correction module using Angular2. Within my child component, I have set up an EventEmitter. import {Component, Input, Output, EventEmitter} from '@angular/core'; ... export class StudyThumbsComponent{ ...

Vue3 and Ionic combined to create a Component that became a reactive object in Vue

Vue is issuing a warning about receiving a Component as a reactive object, which can cause unnecessary performance overhead. The warning suggests using markRaw or shallowRef instead of ref to avoid this issue. However, in my code, I am not explicitly using ...

Is it possible to concurrently hot module reload both the server (.NET Core) and client (Angular)?

Using the command 'dotnet watch run' to monitor changes in server code and 'ng build --watch' for Angular code updates has been successful. It rebuilds the code correctly into directories "bin/" and "wwwroot/" respectively. myapp.cspro ...

What could be the reason behind the error related to react-router-dom?

index.tsx import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); root.render( <React.S ...

Attempting to send a POST request using a string as the payload via http.post

Struggling to make an http.post request from my Angular app to the rest server using this code: Using: import { Http } from '@angular/http'; let headers = new Headers(); headers.append('Content-Type', 'application/json'); ...

Guide to building an interface for an object containing a nested array

While working on my Angular/TypeScript project, I encountered a challenge in processing a GET request to retrieve objects from an integration account. Here is a snippet of the response data: { "value": [ { "properties": { ...

Reducing the amount of text displayed on ion-text to a minimum

HTML: <ion-list *ngFor="let message of messages"> <ion-item lines="none" type="button" button="true"> <ion-grid> <ion-row> <ion-col class="message"> <ion-text> ...

Leveraging Angular 6: Implementing custom scripts on a component basis and verifying their presence

I need some help with a script that I want to run on a specific component only. I've managed to add the script to the component, but there are a few issues that I'm unsure how to fix. When I go to the component, the script is added to the DOM b ...

Issue found in ng-bootstrap.js ng-bootstrap for Angular 6

Recently, I added ng-bootstrap to my Angular project and included its modules. However, upon checking the CLI, an error was displayed. "WARNING in ./node_modules/@ng-bootstrap/ng-bootstrap/fesm5/ng-bootstrap.js 9853:57-75 "export 'ɵɵdefineInj ...

Obtain the coordinates of the pixel in an image on the canvas when a mouse

I am currently working on a project that involves using canvas. I have set a picture as the background of the canvas and would like to be able to get the original pixel point when clicking in the image area. In order to achieve this, I need to convert canv ...

Implementing ng-bootstrap popovers using dynamic data from a database

I am looking to incorporate nb-bootstrap popovers for specific text segments retrieved from a database. While I have successfully integrated ng-popovers in other parts of the code base within the .ts files, attempting to do so with content sourced from th ...

Strategies for resolving npm cache errors within an npm package module

Recently, as I was developing an Angular application, I faced some errors. Here's a snippet of the issues encountered: npm ERR! Unexpected end of JSON input while parsing near '...,"karma-qunit":"*","k' npm ERR! A complete log of this run c ...

reposition content according to screen size

In my web development project, I am utilizing both bootstrap and angular to create a component that includes a menu feature. My goal is to have the menu displayed in the navbar when the screen size is large, but switch it to a dropdown menu on smaller scr ...

The data in my MySQL table is not appearing on an Angular Material table when using Node.js

HTML file content <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef> No. </th> <td mat-cell *matCellDef="let element"> {{ele ...

Measuring the height of an element within its parent component using Angular 4

Check out my demo here I've created a basic parent component along with a child component. Is there a way to retrieve the height of the parent div from within the child component? import { Component, Input, ElementRef, OnInit, ViewChild } from &apo ...

Instead of being viewed in the browser, the CSV file is being downloaded

I'm currently using Jhipster and have a function generated by Jhipster to open files in the browser. However, I'm facing an issue with this function when it comes to opening CSV files - instead of opening in the browser, they are being downloaded ...

What is the process for importing a TypeScript module from the local directory?

I am currently working on a TypeScript module with plans to eventually release it on NPM. However, before publishing, I want to import the module into another project hosted locally for testing purposes. Both projects are written in TypeScript. The TypeSc ...