Getting the parent from a child in Typescript: Best Practices

Querying: In TypeScript, is it possible to retrieve a parent instance from a child instance?

I am aware that casting a child into its parent is a method, however, the child's additional properties still exist in the parent, albeit concealed.

Check out this concise example:

class Animal {
    name = "Animal";
}

class Kid extends Dog {
    name = "Dog";
    power = 'Bark';
}

const a = new Animal();
const d = a as Dog;
console.log(d.power);

The linter may raise a concern about d.power in this code snippet, but rest assured it compiles and functions flawlessly.

Is there an improved approach to achieve this task, without creating a new parent class?

Answer №1

The Child class simply extends the Parent class. When you declare k as Parent (even if this has no effect, since k instanceof Parent is already true), you are essentially saying "treat k as though it possesses all Parent properties and methods".

However, at the end of the day, k is still a Child instance. The naming of your classes suggests that you may not fully grasp inheritance, as they are not named "Parent" and "Child", but rather "Animal" vs "Dog" or "Person" vs "Parent". In general terms outside of programming, we can be certain that a Child is not a 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

Typescript typings for child model/collection structures

I have encountered an issue while trying to implement a Model/Collection pattern with various typings. Both the Model and Collection classes have a method called serialize(). When this method is called on the Collection, it serializes all the Model(s) with ...

What are the steps to incorporating the pick function in TypeScript?

The TypeScript documentation mentions a pick function that is declared but not implemented. In an attempt to create a simplified version, I wrote the following: function pick<T, K extends keyof T>(obj: T, key: K): Pick<T, K> { return { [key]: ...

I'm curious about how to link a JSON field using dot notation in Angular 12 HTML

Does anyone know how to bind a JSON field using dot paths in Angular 12 HTML? For example: //Angular data: any = { name: 'x1', address: { city: 'xyz' } }; field: any = 'address.city'; //Html <input [(ngModel)]="data[ ...

Efficient method to access two arrays simultaneously and combine them into an associative array in JavaScript

When using Ajax to return a table, you have the option of separating column names and row values. Here are two ways to do it: let columns = ["col1", "col2", "col3"]; let rows = [ ["row 1 col 1", "row 1 col 2", "row 1 col 3"] , ["row 2 col 1", "r ...

Tips for dynamically loading a child component and passing data from the child component to the parent component

In my current setup, I have organized the components in such a way that a component named landing-home.component loads another component called client-registration-form.component using ViewContainerRef within an <ng-template>, and this rendering occu ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

Sharing data between components in Angular 2 using the <router-outlet> technique

Having just started exploring Angular 2, I am eager to pass a boolean value from one component to another using <router-outlet> After some research, it seems like the best approach is to utilize a service. My aim is to toggle a boolean variable in ...

What is the best way to modify a variable's value from a nested controller and vice versa?

There seems to be an issue with changing the 'mensaje' variable in both the "padre controller" and the "hijo controller" and visualizing the changes. When clicking on "cambiar padre," the value changes as expected. However, if I then click on "ca ...

Question from a student: What is the best way to transfer information between different classes?

Currently, I am delving into SPFX development. My focus is on constructing a form that incorporates multiple classes in order to gain insight on how they can interact and share data among one another. In this scenario, I have established two distinct clas ...

encountered an issue while accessing a FastAPI-based API

While developing a login feature in Next.js, I encountered an issue when making a request to an API created in FastAPI to retrieve a cookie. The problem arises during the fetch operation on the frontend specifically when setting credentials to 'includ ...

Steps for removing the console warning message: "The use of enableRowSelect has been deprecated. Instead, please utilize rowSelection."

) I have integrated React Data Grid from https://adazzle.github.io/react-data-grid/ multiple times in my application. One thing I noticed is that there is a console warning related to a prop called "enableRowSelect" which indicates whether the prop is bein ...

PrimeNG Component Containing a Dynamic Dialog Instance

I am experiencing an issue with handling dynamic dialogs in PrimeNG. Is there a solution for managing actions on a dialog other than just using the close option? For instance, in the context of the Kendo-UI dialog example, I can specify the content.insta ...

Storing a Vue/JS element reference in a constant using Typescript

In my template, I have one form element and one button element: <button type="submit" id="ms_sign_in_submit" ref="submitButton" class="btn btn-lg btn-primary w-100 mb-5"> </button> Wi ...

Is there a method to implement retries for inconsistent tests with jest-puppeteer?

Currently, I am struggling with an issue where there is no built-in method to retry flaky tests in Jest. My tech stack includes Jest + TypeScript + Puppeteer. Has anyone else encountered this problem or have any suggestions for possible solutions? I attem ...

Dispatching an asynchronous function error in React with TypeScript and Redux - the parameter type is not assignable to AnyAction

Currently, I am in the process of developing a web application that utilizes Firebase as its database, along with Redux and TypeScript for state management. Within my code, I have a dispatch function nested inside a callback function like so: export const ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Tips on changing the name of a property within an object using JavaScript

While this question may appear to be a duplicate, there is actually a distinction. I am attempting to provide a new key that does not contain any spaces. {order_id :"123" , order_name : "bags" , pkg_no : "00123#"} My goal is ...

Using .on('mouseover', d => ..) does not yield the same `d` value as using .attr('foo', d => ..) in D3.js

I'm facing an issue with a mouseover tooltip in Observable that seems to fail when I transfer it to a Grafana plugin using React, D3, and Typescript. The technique I followed can be found in this article: Link to Article To simplify the code and deb ...

Create a new instance of a class without considering letter case

Currently, I am dealing with a dilemma. My class name is stored in a variable, and I need to create an instance of it. However, the problematic part is that I cannot guarantee that my variable has the same casing as the class name. For example: //The cla ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...