Different types require individual declarations for their private properties

While immersing myself in learning Angular, a TypeScript-based framework, I encountered an intriguing error:

The class 'SnackbarService' is mistakenly extending the base class 'MatSnackBar'. There are separate declarations for types of a private property '_overlay'.

This error revealed itself as I attempted to extend MatSnackBar from @angular/material.

Here's the snippet of my code causing this issue:

import { MatSnackBar } from '@angular/material';
import { Overlay } from '@angular/cdk/overlay';
import { LiveAnnouncer } from '@angular/cdk/a11y';
...

export class SnackbarService extends MatSnackBar {

  constructor(
    private _overlay: Overlay, 
    private _liveAnnouncer: LiveAnnouncer,
    ...
  ) {
    super(_overlay, _liveAnnouncer, ...);
    }
  }
}

I would greatly appreciate any assistance or insights on why this is happening. Thank you!

Answer №1

The reason for this issue is that by specifying the constructor to accept a private _overlay parameter, you inadvertently created a new instance of _overlay, which conflicts with the one already defined in the base class MatSnackBar.

To resolve this, simply remove the private keyword from the parameter declaration and inherit it from the base class instead. Repeat this for any other constructor parameters as well.

export class SnackbarService extends MatSnackBar{

  constructor(
    _overlay: Overlay, 
    _liveAnnouncer: LiveAnnouncer,
    ...
  ) {
     super(_overlay, _liveAnnouncer, ...);
    }
  }
}

You will still be able to access these parameters using this.

Answer №2

In situations like this, discrepancies in dependencies' versions can cause issues. [Taking into account the perspective of Typescript]

For instance, if your application X is using version 1.0 of a package Y, and also version 1.0 of package Z. However, package Z relies on a different version of package Y, let's say version 2.0.

This results in having two distinct classes with identical names throughout the overall building process. To resolve this issue, it is essential to either upgrade package Z or upgrade package Y, in order to ensure consistency in versions across the entire application.

Answer №3

As a newcomer, I wasn't able to comment on the previous answer. I also share the opinion that using 'protected' instead of 'private' is a better approach for this particular scenario, rather than simply removing the modifier. When dealing with a parent class and wanting its properties/methods to be accessible to the child class, it's best to use protected.

https://www.typescriptlang.org/docs/handbook/classes.html#understanding-protected

One question in the comments was about why using protected resolves the issue. The link above provides an explanation (albeit simplified). It involves how access modifiers impact property inheritance differently. Hopefully, this sheds some light on the conceptual reasoning behind it.

Because private declarations are specific to a class, they cannot be inherited by child classes, resulting in duplication of properties when merging the child and parent objects (leading to errors).

Using protected ensures that the variable is inherited by the child class, allowing them to share the same variable. Even if the child redeclares the variable, it is simply merged with the inherited one in the final object. This offers the same non-public benefits while maintaining inheritance within the derived class.

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

Guide to excluding all subdependencies using webpack-node-externals

My current setup involves using webpack to bundle both server assets and client code by specifying the target property. While this configuration has been working well, I encountered an issue where webpack includes all modules from node_modules even for ser ...

Changing an Array into JSON format using AngularJS

I am attempting to switch from a dropdown to a multiselect dropdown. <select name="molecularMethod" class="form-control" ng-model="request.molecularMethod" multiple> It is functioning properly. However, when items are selected, it generates an arra ...

Conquering cross-origin resource sharing (CORS) using XMLHttpRequest without relying on JSONP

Appreciate your time in reading this inquiry! For the past few days, I've been grappling with an AJAX request issue. Despite scouring through numerous answers on Stack Overflow, I'm still unable to find a resolution. Any assistance would be grea ...

I'm interested in learning how to send JSON in HTTP GET parameters using express and Node. Can you provide some guidance on

Currently, I am utilizing express and aiming to forward a JSON object to my HTTP GET route function: app.get('/myRoute/:data', (req, res) => {} Since using HTTP POST is not an option for me, I need to find a way to pass the JSON in the URL. ...

Display the following information as you iterate through an array in TypeScript within a React component

Currently, I am working on adding data to two separate arrays in a React TypeScript project. const [deviceNames, setDeviceNames] = useState<Array<string>>([]) const [serialNumbers, setSerialNumbers] = useState<Array<string>>([]) ...

"Is there a way to update the value of a variable within $scope when a specific action

Is it possible in Angular to change the value of $scope.complete to false when a specific URL is clicked by the user? I display a credit card form based on the value of this variable. Initially, the value is set to true or false depending on the data from ...

Is it possible to modify the class within TypeScript code while utilizing the CSS library for styling?

In my custom style sheet coustume-webkit.css, I have the following code snippet: .tabella .pagination > li:last-child > a:before, .tabella .pagination > li:last-child > span:before { padding-right: 5px; content: "avanti"; ...

Can anyone provide guidance on incorporating lodash into an Ionic 2 project?

Recently, I began diving into a new project that involves Ionic 2. TypeScript is still fairly new to me, and I've been brainstorming ways to integrate lodash into my project. Have any of you tackled this before and can offer guidance on how to achiev ...

Why is Jquery's .addClass and .removeClass not functioning as expected?

Recently, I implemented a feature in my code where clicking on an item would display a contextual menu (in the form of a div) that allows users to cut and paste list items. To control the functionality, I added a 'disabled' class to the buttons w ...

What is the best way to access the ngModel value from an input tag within an AngularJS4 component?

I'm still getting the hang of angularjs4 and I've been working with angular-cli. One thing I need to do is retrieve the value of an ngModel from an input tag in my component. How can I access the value that's been entered into the input fiel ...

Identify a click event on a sortable element that has been dynamically added using the

I am currently working on creating 2 sortable lists, where the items are added using append(). Everything seems to be working perfectly fine, but I am facing an issue with making the items move between the lists upon clicking. For some reason, the click e ...

Strategies for successfully sharing MongoDB database connections between routes in NodeJS

I am trying to figure out how to pass the connection to mongo from index.js to other routes. I believe that creating a separate file with the necessary instructions for defining the database connection could be a solution, but I'm not sure how to impl ...

When the text exceeds the space available, it will automatically flow into a new column in lower

Is there a way to make text content flow into a column that appears next to it when the window height is decreased? Essentially, I am looking for a solution where the text can smoothly transition to a dynamically created column. Are there any jQuery plugi ...

How can dynamic x and y values be used to create moving waves on Canvas in HTML5?

My dynamic array values consist of x and y... Incorporating these x and y values, I want to create varying sine, triangular, square, and sawtooth waves on an HTML5 canvas... ...

Best Method for Confirming Deletion in Data Table with Shadow and UI

I have a query regarding the Shadcn/UI - Data Table component. In my case, I am working with a list of users where each row has a delete button in the last column. Upon clicking the delete button, a confirmation dialog pops up. Currently, I am implementi ...

A function with a specific name for sorting a multidimensional object based on a specified sub-key's value, without anonymity

My data consists of a collection of objects, not an array: var people = {}; people['Zanny'] = {date: 447, last: 'Smith'}; people['Nancy'] = {date: 947, last: 'William'}; people['Jen'] = {date: 147, last: &a ...

Combining union types with partial types in TypeScript: A guide

Consider the following type in TypeScript: type Input = { a: string b: number } | { c: string } How can we merge it into a partial type like this: type Result = { a?: string b?: number c?: string } We are seeking a type Blend<T>: type B ...

Failed to pass through invalid parameters "recordIds", "datasources" while navigating in VUE

While working with Vue, I encountered an issue when trying to pass parameters from one route to another. Here is what my target route looks like: { path: '/record-modification', name: 'recordModification', component: recordModi ...

Leveraging moment.format Function in Angular within an HTML Context

Is there a way to implement the moment.format method in HTML? Currently, I am utilizing the toLocaleDateString method to showcase an array of dates: <ng-template let-event> <div>{{event.date.toLocaleDateString(' ...

Combine two arrays into one

When attempting to combine two arrays, the result looks like the image linked below: https://i.sstatic.net/3FWMZ.png I want the merged array to resemble the following example: {0: {…}, storedArr: Array(2)} 0: address: "ifanio de los Santos Ave, Ma ...