Accessing Child Object functions using parent type variable

I am facing an issue with storing the instance of a Child class in a parent variable. Even after doing so, I find that when trying to call the Child's functions using the parent variable, it does not work as expected. How can I effectively utilize the Child functions in this scenario?

class Parent{
  public teach(){
   console.log("Parent teaching");
  }
}

class Child extends Parent{
  public learn(){
    console.log("Child Learning");
  }
}

Parent x = new Child();

x.learn(); //Attempting to call Child function from Parent variable

Answer №1

In typescript, the concept of "Upcasting" does not exist.

Parent a = new Child();
a.learn(); //This method is not available in the parent class

This piece of code will not function as intended.

Answer №2

To have the parent invoke the child method, one possible implementation is as follows:

abstract class Parent {
  abstract teach();
}

class Child extends Parent {
  public teach(){
    console.log("Child Teaching");
  }
}

const a: Parent = new Child();
a.teach(); // action performed

Answer №3

After conducting some research, I was able to discover the solution. In C++, dynamic cast can be used to check the type during runtime. Unfortunately, this functionality is not available in JavaScript. Therefore, the recommended approach is to utilize "Type Assertion".

let b = a as Child;
b.learn();

Subsequently, b can now be utilized as a Child object.

To delve deeper into this topic:

https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

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

Using Angular 6 to load external HTML files with CSS inside a router-outlet

I'm currently working on creating a json-based dynamic template using Angular 6. There are certain scenarios where I need to fetch external html content (which could be stored in a database) along with its corresponding css (also stored separately in ...

When accessing a REST API in an Angular 16 project, errors may occur. However, if the API is directly called via POSTMAN or a browser, the expected data will be displayed

angular project using service for data retrieval fetchData() { this.regionService.getAllRegion().subscribe(data => { this.regionValue = data; })} Fetching Data from the API Endpoint getAllRegion(): Observable<RegionI> { const regionUrl ...

Tips for simulating a "nested" angular service within a component using jest

I'm looking to create a unit test for an Angular Component using Jest. The component, which is built on Angular version 7.2.0, interacts with a nested service through this.api.manageUser.getUsersStats(). My goal is to verify if this method is being ca ...

Create a pinia state by defining it through an interface without the need to manually list out each property

Exploring the implementation of state management (pinia) within a single-page application is my current task. We are utilizing typescript, and I am inquiring about whether there exists a method to define a state based on an interface without needing to ret ...

The NativeScript error code TS2554 is indicating an expectation of 1 argument, however, none were provided

Trying to utilize the native camera API with NativeScript without any plugins has presented an error when attempting to use the takePicture function: app/shared/camera/camera.service.ts(23,39): error TS2554: Expected 1 argument, but received 0. app/sh ...

`ìf the navigation button is clicked, the onSlideChange function runs twice`

For my project, I implemented multiple slides per group using Swiper.js and React@^18. However, I encountered an issue where the onSlideChange function runs twice when clicking the navigation button at the first slide's group. This causes it to skip t ...

I'm wondering why my JWT token appears as null on the backend while it is not null on the frontend

I'm having trouble with a GET request to my mLab database. I included a JWT token in the request and verified it on both the client and server side. Strangely, it appears correctly on the client but as null on the server. Any assistance on this matter ...

Can two Angular element components be utilized simultaneously on a single page in Angular 6?

Currently, I'm attempting to host independent Angular elements that can be seamlessly integrated into a non-Angular webpage. Everything works perfectly fine when there's only one element on the page, but as soon as I try to load two or more, I en ...

Angular 15 is unfortunately not compatible with my current data consumption capabilities

I'm currently facing an issue with Angular 15 where I am trying to access the "content" element within a JSON data. However, when attempting to retrieve the variable content, I am unable to view the elements it contains. import { Component, OnInit } ...

Angular 2+ encountering an internal server error (500) while executing an http.post request

Here is my service function: public postDetails(Details): Observable<any> { let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: cpHeaders }); return this.htt ...

Using TypeScript to transform a tuple type into an object

When dealing with a tuple type like: [session: SessionAgent, streamID: string, isScreenShare: boolean, connectionID: string, videoProducerOptions: ProducerOptions | null, connection: AbstractConnectionAgent, appData: string] there is a need to convert it ...

Enabling withCredentials in Angular 6 for every HttpClient request is crucial for maintaining consistent authentication and

Is there a method to set { withCredentials: true } as the default for every httpclient call, instead of having to add it manually each time? import { HttpClient } from '@angular/common/http'; ... constructor(private httpclient: HttpClient) { } ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Angular 6: Endlessly Scroll in Both Directions with Containers

Does anyone know of a library for angular 6 that allows for the creation of a scrollable container that can be scrolled indefinitely in both directions? The content within this container would need to be generated dynamically through code. For example, ...

Tips for running a dry default with Angular CLI

Query: Can dry-run be set as the default in a configuration? Purpose: Enabling dry-run by default simplifies the learning process by minimizing clean-up tasks if the command is not correct. This can encourage users to always perform a test run before exec ...

What is the cause of the display name missing in the Material-UI Typescript ListItemLink example when using React.forwardRef?

Explore the Material-UI documentation guide on incorporating Typescript in an example demonstrating the creation of a ListItemLink component: Visit the official documentation function ListItemLink(props: ListItemLinkProps) { const { icon, primary, to ...

Deleting data from Firebase in Angular can be easily done using the AngularFire library. By

I am attempting to remove specific values from my Firebase database. I need to delete this entry from Firebase: https://i.stack.imgur.com/CAUHX.png So far, I have tried using a button to trigger the delete function like this: <div class="single-bfunc ...

The correct procedure for refreshing a page in Angular 8

Note: I found some code snippets online but, after testing them out, I have doubts about their reliability due to inconsistencies. In my script, I have developed two utility functions - one for moving to the parent node and another for reloading the curre ...

Unable to access Angular 6 Application running on AWS EC2 instance via public IP address

Encountering difficulties accessing an Angular 6 application via public IP over the internet. To troubleshoot, I initiated a Windows EC2 instance and proceeded to install Node.js and Angular CLI by executing the following commands- npm install -g @angular ...

What is the definition of the style directive?

While I have a good amount of experience with Angular, there are still areas where my knowledge falls short. I've been exploring the directive that allows for setting specific styles on an element, like so: <div [style.color]="'red'"> ...