"Error: In TypeScript, the Child Method is not recognized within the Parent

I'm a newcomer to TypeScript and object-oriented programming. I am attempting to use a method from a child class in the parent class, but for some reason, the method is not being recognized.

Below is my Child class:

import {Ouvrage} from "./Class_Ouvrage";
import {Emprunt} from "./Class_Emprunt";
import {Adherant} from "./Class_Adherant";

export class Volumes extends Ouvrage {

private _NombreExemplaire: number;
private _NombreExemplaireEmpruntes: number;
private _auteur: string;

public get NombreExemplaire(): number {
    return this._NombreExemplaire;
}

set NombreExemplaireEmpruntes(value: number) {
    this._NombreExemplaireEmpruntes = value;

}

get NombreExemplaireEmpruntes(): number {
    return this._NombreExemplaireEmpruntes;
}

get auteur(): string {
    return this._auteur;
}

constructor(Pnombreexemplaire: number, Pnombreexemplairemprunte: number, Pauteur: string, PID: number, PTitre: string, Pdate: Date) {

    super(PID, PTitre, Pdate);
    this._auteur = Pauteur;
    this._NombreExemplaire = Pnombreexemplaire;
    this._NombreExemplaireEmpruntes = Pnombreexemplairemprunte;


}

descriptionVolume(): string {
    return "l'auteur de ce volume s'apelle : " + this.auteur + " , il reste " + this.NombreExemplaire + "disponible(s)" + " Le nombre de volumes déja emprunté, s'éleve a " + this.NombreExemplaireEmpruntes;
}



 public NbExemplaireDispo() : number{
        return this.NombreExemplaire - this.NombreExemplaireEmpruntes;
    }

}

Here is the parent class where I would like to call the method:

import {Volumes} from "./Class_Volume";
import {Adherant} from "./Class_Adherant";    
export class Ouvrage{
    private _id : number;
    private _titre : string;
    private _date : Date;
get id(): number {
    return this._id;
}


get titre(): string {
    return this._titre;
}

get date(): Date {

    return this._date;
}

constructor(PID : number, PTitre : string, Pdate : Date) {


    this._id = PID;
    this._titre = PTitre;
    this._date = Pdate;


}

descriptionOuvrage() : string{

    return "Cet ouvrage s'apelle " + this.titre + " et il est sorti le " + this.date+" ";
}

 this.NbExemplaireDispo();

}

How can I get NbExemplaireDispo() to work?

As mentioned earlier, since I am new to oop, is it considered good practice to make this kind of call?

Thank you!

Answer №1

Having trouble using a child method from the parent class? The method might not be recognized due to some reasons.

...

If you're new to object-oriented programming, it's generally not recommended for parent classes to call methods defined in child classes. This can lead to issues with instances and inheritance.

For example, consider this scenario where a parent class tries to call a method defined in a child class:

class Parent {
    parentMethod() {
        this.childMethod(); // This won't work as intended
    }
}
class Child extends Parent {
    childMethod() {
        // Method implementation
    }
}
const p = new Parent();
p.parentMethod(); // An error would occur because `parentMethod` is calling `childMethod` which belongs to `Child`

This issue becomes even more complex when dealing with multiple child classes that may or may not have the required method defined.

To avoid such pitfalls, it's best practice to define methods in the parent class and override them in child classes if needed. Here's an example:

class Parent {
    parentMethod() {
        this.theMethod();
    }
    theMethod() {
        // Default implementation
    }
}
class Child extends Parent {
    theMethod() {
        // Customized method for child class
    }
}
const p = new Parent();
p.parentMethod(); // Works as expected

Alternatively, you could use an abstract method in the parent class to enforce implementation in child classes:

class Parent {
    parentMethod() {
        this.theMethod();
    }
    abstract theMethod();
}
class Child extends Parent {
    theMethod() {
        // Implementing the abstract method
    }
}
const c = new Child();
c.theMethod(); // Executed successfully
const p = new Parent(); // Compilation error: Cannot instantiate abstract class `Parent`

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

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

Developing React component libraries with TypeScript compared to Babel compiler

Currently, I'm utilizing the babel compiler for compiling my React component libraries. The initial choice was influenced by Create React App's use of the same compiler. However, I've encountered challenges with using babel for creating libr ...

Best practices for annotating component props that can receive either a Component or a string representing an HTML tag

What is the correct way to annotate component props that can accept either a Component or a string representing an HTML tag? For instance, imagine I have a component that can receive a custom Component (which includes HTML tags like div, p, etc.). The cod ...

Steps for setting up single sign on in an Angular 2 application

Currently, I am working on a web application that has been developed using angular2. One of the requirements for this application is to incorporate a single sign-on feature, where users do not have to manually input their login credentials. Instead, the ap ...

One way to incorporate type annotations into your onChange and onClick functions in TypeScript when working with React is by specifying the expected

Recently, I created a component type Properties = { label: string, autoFocus: boolean, onClick: (e: React.ClickEvent<HTMLInputElement>) => void, onChange: (e: React.ChangeEvent<HTMLInputElement>) => void } const InputField = ({ h ...

Using CamanJs in conjunction with Angular 6

Struggling to integrate camanjs with Angular 6? Wondering how to add the JavaScript library and use it within an Angular project when there are no types available on npm? Here are the steps I followed: First, install Caman using npm. Next, add it to ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

How can you define the types of function arguments when destructuring arguments in TypeScript?

TS throws an error that states: Error:(8, 20) TS7031: Binding element 'on' implicitly has an 'any' type. Error:(8, 24) TS7031: Binding element 'children' implicitly has an 'any' type. Below is the function I am wor ...

Images with spaces in their names are failing to load in React Native

I am currently trying to utilize an image within my react native application. At this point, my code is very minimal. The following code snippet is all I have for now: import React from 'react'; import { ScrollView, View, Text } from 'reac ...

Utilizing an Observable in an Angular 6 service to ensure proper synchronization with Okta token present in local storage

Within my application, I have implemented third-party authentication to facilitate user login and store a token in their local storage. To enhance the user experience, I am developing a service to cache profile information. This service utilizes the user&a ...

Leveraging Angular 4 with Firebase to extract data from a database snapshot

My dilemma lies in retrieving data from a Firebase DB, as I seem to be facing difficulties. Specifically, the use of the "this" operator within the snapshot function is causing issues (highlighted by this.authState.prenom = snapshot.val().prenom) If I att ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Having trouble with clearInterval in React TypeScript?

I have been encountering issues with the clearInterval function in TypeScript for React. I am not sure why the interval is not being cleared. To address this problem, I defined a variable let interval_counter;, and used it as follows: interval_counter = ...

Utilizing Angular 5 routerLink for linking to absolute paths with hash symbols

I am facing an issue with a URL that needs to be opened in a new tab. Unfortunately, Angular generates this URL without the # symbol. Currently, we have implemented the following: <!-- HTML --> <a title="Edit" [routerLink] = "['/object/objec ...

Can an L1 VPC (CfnVpc) be transformed into an L2 VPC (IVpc)?

Due to the significant limitations of the Vpc construct, our team had to make a switch in our code to utilize CfnVpc in order to avoid having to dismantle the VPC every time we add or remove subnets. This transition has brought about various challenges... ...

Typescript raises an error when providing a potentially null value (that is not null) to an unnamed callback function

When dealing with a property that starts as null, how can I pass it to an anonymous callback function expecting a non-null value without TypeScript throwing errors? I've tried wrapping the function call in an if statement to check for null at the cal ...

A guide to testing the mui Modal onClose method

When using material UI (mui), the Modal component includes an onClose property, which triggers a callback when the component requests to be closed. This allows users to close the modal by clicking outside of its area. <Modal open={open} onCl ...

Unable to locate the term "module"

I've been working on a TypeScript file that includes an exported function called sum: This script is meant to be run in Node.js. function sum(a:number):number{ return a; } module.exports.sum=sum; I'm encountering some issues and I'm not ...

Struggling to make the paste event function in Typescript

Here is a snippet of my Typescript code: const pasteFn = (e: ClipboardEvent) => { const { clipboardData } = e; const text = clipboardData?.getData('text/plain'); console.log(text); }; window.addEventListener('paste', pas ...

Determine through programming whether an ng-content slot has been filled in Angular

I have developed a dynamic Angular component that utilizes content projection and slots in the following way: <div class="content-wrapper"> <div class="short-wrapper" [style.opacity]="expanded ? 0 : 1"> ...