In TypeScript, a sub class method invoking the super method will return the type of the parent class

I am grappling with the concept of inheritance in typescript. I am facing an issue where I cannot seem to return the child type when invoking super within a method. Can someone shed light on why this example fails to return the child type? How does the use of as impact it? Is there a workaround to achieve the desired behavior?

class Parent {
    _value: number
    constructor(value: number){
        this._value = value
    }
    add(x: Parent): Parent {
        return new Parent(x._value + this._value)
    }
}

class Child extends Parent {
    constructor(value: number) {
        super(value)
    }
    add(x: Child): Child {
        return super.add(x) as Child
    }
}

let a = new Child(10)
let b = new Child(5)
let c = a.add(b)

console.log(a)
console.log(b)
console.log(c)

Output:

Child { _value: 10 }
Child { _value: 5 }
Parent { _value: 15 }

Answer №1

When dealing with this type of polymorphism, it is recommended to utilize "new this.constructor()" and set the return type as "this" for TypeScript. Following these steps eliminates the need to override the method.

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

"Following successful POST login and session storage in MongoDB, the session is unable to be accessed due

When sending login data by POST with the credentials: 'include' option from client server 5500 to backend server 3000, I ensure that my session data is properly stored in MongoDB thanks to the use of 'connect-mongodb-session'. In the ba ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

Exploring the power of EJS with conditional logic

Can someone help me figure out why EJS is not evaluating to the else branch in my code? I'm using EJS version 3.1.5 with express version 4.17.1 and typescript. ReferenceError: /home/pauld/tscript/dist/views/index.ejs:12 10| </head> 11| & ...

Eradicate lines that are empty

I have a list of user roles that I need to display in a dropdown menu: export enum UserRoleType { masterAdmin = 'ROLE_MASTER_ADMIN' merchantAdmin = 'ROLE_MERCHANT_ADMIN' resellerAdmin = 'ROLE_RESELLER_ADMIN' } export c ...

Ways to resolve sonar problem "Ensure this function is updated or refactored to avoid duplicating the implementation on line xxx"

SonarQube has detected duplicate functions in specific lines: beneficiaires.forEach(beneficiaire => { () => { Below are the identified functions: affectPercentageToBeneficiares(beneficiaires: BeneficiaryData[], sum: number) { let numberOfBenefi ...

Utilizing a conditional ngIf statement in HTML or incorporating a variable within typescript for logical operations

When working with our application, we often need to display or hide a button based on specific logic. Where do you think it is best to define this logic and why? In HTML: *ngIf='logic goes here' //Or *ngIf='someBoolean' and in Type ...

Please input the number backwards into the designated text field

In my react-native application, I have a TextInput where I need to enter numbers in a specific order such as 0.00 => 0.01 => 0.12 => 1.23 => 12.34 => 123.45 and so on with each text change. I tried using CSS Direction "rtl" but it didn' ...

Using ngModel to bind data within an Angular dialog box

I'm facing an issue with my project where changes made in the edit dialog are immediately reflected in the UI, even before saving. This causes a problem as any changes made and then canceled are still saved. I want the changes to take effect only afte ...

Collapsible list in Angular2 sidenav: ensuring only one sublist remains open

Presenting a functional sidenav demo with Angular 2, TypeScript, and Material Design components. The sidenav features a UL, with the Sites and Users anchors expanding to display their own sub-list. Check out the Plunker here Here is the HTML code for the ...

Receiving a null value when accessing process.env[serviceBus]

Currently, I am focusing on the backend side of a project. In my environment, there are multiple service bus URLs that I need to access dynamically. This is how my environment setup looks like: SB1 = 'Endpoint=link1' SB2 = 'Endpoint=link2&a ...

Problem with Invoking method of parent component from child component in Angular 4

Despite having all my event emitters set up correctly, there's one that seems to be causing issues. child.ts: @Component({ ... outputs: ['fileUploaded'] }) export class childComponent implements OnInit { ... fileUploaded ...

Creating a TypeScript class without using the prototype method

Recently delving into TypeScript and encountering a perplexing issue for which I can't seem to locate a satisfactory explanation... Let's suppose I have a function: function test() { function localAccessMethod() { console.log(' ...

What is the best way to invoke a class function within a static object?

Here's an example for you: export class MyClass { myString: string; constructor(s: string) { this.myString = s; } myFunction() { return "hello " + this.myString; } } export class MainComponent { static object1: MyClass = JSON. ...

I am looking for unique values from a duplicate string that is separated by commas in TypeScript

Using TypeScript, I am trying to extract unique values from a list of comma-separated duplicate strings: this.Proid = this.ProductIdList.map(function (e) { return e.ProductId;}).join(','); this.Proid = "2,5,2,3,3"; The desired output is: this. ...

Just made the switch to Mongoose 5.12 and hit a snag - unable to use findOneAndUpdate with the $push operator

After upgrading to Mongoose 5.12 from 5.11 and incorporating Typescript, I encountered an issue with my schema: const MyFileSchema = new Schema<IMyFile>({ objectID: { type: String, required: true }, attachments: { type: Array, required: false ...

Transform the string property extracted from the API into a JSON object

When making a request to an API, the data returned to the front end is in the following format: { name: 'Fred', data: [{'name': '"10\\" x 45\\" Nice Shirts (2-pack)"', 'price' ...

Exploring the parent-child relationship of three components within Angular 2

Currently, I am developing a shopping cart using Angular 2. The application consists of two components - one for categories and another for product listings, both included in the main app component as children. However, I'm facing an issue where these ...

Unable to determine model dependency in Nest

I encountered an issue where Nest is unable to resolve dependencies. The error message from the logger reads as follows: [Nest] 39472 - 17.08.2023, 05:45:34 ERROR [ExceptionHandler] Nest can't resolve dependencies of the UserTransactionRepository ( ...

Implementing HTTP GET and POST requests in Angular 2 allows for the functionality of displaying, adding, and deleting objects within a list

Hey there, I'm completely new to dealing with HTTP and fetching data from the server. I've been scouring through various tutorials, examples, and questions on different platforms, but unfortunately, I haven't been able to find exactly what I ...