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

Image Box is effortlessly moved around by dragging and dropping

While working on my HTML code in Angular 9, I'm trying to figure out where I need to make changes to display image previews instead of broken images in the browser: <div cdkDropListGroup> <div class="box-container"> <h2>TABLE ...

Installing Angular 4 in Visual Studio 2017

Looking to build an Angular web application using Visual Studio 2017. Starting with a new project by selecting Asp.net Web application with Empty template. Feeling unsure about which files need to be copied/included in the project based on the attached sc ...

Is it possible to insert data into SQL Server from an Angular application without relying on .NET Core?

Is there a way to extract data from an Angular-made form and store it in a SQL Server table without the need for .NET Core? ...

Ending the Infinite Scroll in Ionic 3 When Data Runs Out

I am having an issue with my json data where I need to figure out how to stop the infinite scroll once there is no more data available. Can anyone help me implement this feature? Below is the code snippet for reference: handleDataLoad(currentCount) ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

What are the steps to fixing the TS2722 error that says you cannot call a possibly 'undefined' object?

Here is a snippet of code from my project: let bcFunc; if(props.onChange){ bcFunc = someLibrary.addListener(element, 'change',()=>{ props.onChange(element); //This is where I encounter an error }) } The structure of the props ...

Clicking on the React Bootstrap Checkbox within the Nav component does not trigger a rerender of the NavItem component

Encountering an unusual issue while using a Nav and NavItem with a Checkbox from React Bootstrap. What I've noticed is that when clicking directly on the checkbox instead of the NavItem button, the checkbox does not re-render correctly even though my ...

Is it possible to invoke a component's function within the click function of a Chartjs chart?

How do I trigger a function in my Component from an onclick event in my chart.js? export class ReportesComponent implements OnInit { constructor(public _router: Router, private data: ReporteService) {} this.chart = new Chart('myChart', { ...

Is the validity of the expression !args.value || args.value.length true?

After analyzing this segment of code, I noticed an interesting expression: !args.value || args.value.length For instance, consider the following scenario: let v = {}; console.log(!v.value); //outputs true console.log(v.value); //outputs undefined con ...

There was an issue with compiling the template in the module. It was unable to locate the component in relation to the [

I have organized my project folder structure as follows: Inside the cable folder, there is a component path defined as: /folder1/folder2/dialogs/changes-dialog/details-wizard/add-packages/new-package-definition/package-selection/package-selection.componen ...

Tips for deploying an Angular 2+ application on the OpenShift platform

I successfully developed an Angular application on my Windows PC, and now I am facing challenges in deploying it on Red Hat OpenShift. Despite searching for guides online, I have not been able to find helpful resources. If anyone has experience with deploy ...

What is the rationale behind TypeScript's decision to permit omission of "this" in a method?

The TypeScript code below compiles without errors: class Something { name: string; constructor() { name = "test"; } } Although this code compiles successfully, it mistakenly assumes that the `name` variable exists. However, when co ...

Is there a way to substitute the HOC with a single call and solely modify the prop?

One issue I've encountered in my project is the repetitive use of a Higher Order Component (HOC) for the header. Each time it's used, the props are set to determine whether header links should be displayed or not. My objective is to streamline th ...

Counting up in Angular from a starting number of seconds on a timer

Is there a way to create a countup timer in Angular starting from a specific number of seconds? Also, I would like the format to be displayed as hh:mm:ss if possible. I attempted to accomplish this by utilizing the getAlarmDuration function within the tem ...

Is it possible to create a prototype function within an interface that can group items in an array by a specific property, resulting in an array of objects containing a key and corresponding array of values?

I've been working on this code snippet and I'm trying to figure out how to make it work: Array<T>.groupBy<KeyType> (property): {key: KeyType, array: Array<T> }[]; The code looks like this: type ArrayByParameter<T, KeyType = ...

How can a mock document be utilized in a unit test for an imported TypeScript dependency?

To effectively unit-test a legacy TypeScript class, I am seeking ways to mock the document object. The class has dependencies on another class (View.ts), which in turn relies on a 3rd party module that further depends on the existence of the document. The ...

Steps for creating a border around a container Div:1. Set the width and

Seeking assistance in bordering a div with 4 fa-icons inside. The parent div is named Container, and as a result, the border is creating excessive padding on the left and right sides horizontally. Attempted nesting bootstrap grids without success. Can anyo ...

Service stub in Angular containing static properties

I am faced with a challenge in my service that requires the use of APP_INITIALIZE to set a static property value. Another service within my system depends on this property, so I need to stub this service with the static value. However, using provide is n ...

Stop webpack from stripping out the crypto module in the nodejs API

Working on a node-js API within an nx workspace, I encountered a challenge with using the core crypto node-js module. It seems like webpack might be stripping it out. The code snippet causing the issue is: crypto.getRandomValues(new Uint32Array(1))[0].toS ...

Transferring information to a deep-level interface

I am currently working on creating an object that aligns with my interface structure. Success Story export interface ServiceDataToDialog { id: number, service: string, } constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComp ...