Error encountered in TypeScript when attempting to override a method: The distinction between Overriding and Overloading

In my Angular 9 application, I have two classes that I am using as services: class A and class B, where class B extends class A.

class A{
 exportToCSV(data: any[], headers: any[]){
      ....
   }

}


class B extends A{
 exportToCSV(data: any[], headers: any[], metadata : any){
      ....
   }

}

An error is being thrown:

Property 'exportToCSV' in type 'B' is not assignable to the same property in base type 'A'. Type '(data: any[], headers: any[], metadata : any) => void' is not assignable to type '(data: any[], headers: any[]) => void'.ts(2416)

According to the documentation provided at https://www.typescriptlang.org/docs/handbook/classes.html

this should work, but it doesn't. Making the metadata optional however, makes it work (https://medium.com/@kevinkreuzer/typescript-method-overloading-c256dd63245a).

I am attempting to override the method, but it seems to be overloading instead. Can someone clarify why this is happening?

Answer №1

This situation does not involve function overloading as outlined in TypeScript, where a function can have multiple call signatures that must all align with a single implementation. In this instance, the B class simply replaces the exportToCSV() method from class A, even though this replacement is deemed invalid.


By replacing the exportToCSV() method from class A with one from class B, you are violating the agreement between the two classes. The fundamental concept at play here is substitutability (or the Liskov Substitution Principle), which stipulates that a subclass should seamlessly replace its superclass without any complications. For example:

const a: A = new B();
a.exportToCSV([], []); 

It is crucial to ensure that the methods are compatible if you intend for B to act as a substitute for A.

Link to code on TypeScript Playground

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 static typing in Visual Studio for Angular HTML

Is there a tool that can validate HTML and provide intellisense similar to TypeScript? I'm looking for something that can detect errors when using non-existent directives or undeclared scope properties, similar to how TypeScript handles compilation er ...

Is it possible to utilize an array of numbers as a data source in ng2-smart table?

Hey there, I'm currently facing an issue with populating ng2-smart-table with an array of numbers. When I try to display the table, all I see is 6 empty rows like this: https://i.stack.imgur.com/DZJjq.png Here's the code for the table: <ng2- ...

The Bootstraps CSS style doesn't seem to be working properly or being overridden within an Angular

I have seen similar questions asked before, but none of the solutions provided have fixed my issue. It appears that the styles are being applied initially but then overridden by something else, and I am unable to identify what is causing this. The only r ...

Filtering without the includes() Method

I have two Objects that are structured as follows: export const recipes: Recipe[] = [ new Recipe( id: "Green", scenario: ["1", "2"]), new Recipe( id: "Blue", scenario: ["1", "2","2"]) ]; export const scenarios: Scenario[] = [ new Scenario( id: "1 ...

Navigate in Angular to the server but add token headers using an interceptor

I need to incorporate authenticated file serving from the backend into my Angular routing: { path: 'files/:id/:name', pathMatch: 'full', ??? } My HTTP interceptor is already set up to include token headers in other requests. What I wan ...

Eliminating the InMemoryWebApiModule in the production configuration of webpack for Angular applications

Currently, I am utilizing the InMemoryWebApiModule to simulate my data during development, but I want to prevent it from being used in a production environment. Is there a method to exclude it from being used in production on webpack? I have been attempt ...

Refresh the Angular component following updates to the store

Working with NGRX/Redux for the first time, I am puzzled by why my component fails to update after adding a new item to an array in the store. Within my main component, these properties are defined: productLines$: Observable<ProductionLine[]>; produ ...

Having trouble invoking the "done" function in JQuery following a POST request

I am currently working on a Typescript project that utilizes JQuery, specifically for uploading a form with a file using the JQuery Form Plugin. However, after the upload process, there seems to be an issue when trying to call the "done" function from JQue ...

The process of transferring a list of objects to another in Typescript

There seems to be an issue with copying values from "all" to "available" and sometimes not getting the value from "available" as well. I've tried multiple methods like using slice(), Array.from(), and simply assigning with =, but none of them seem to ...

Angular is showing an error stating that the type 'EventEmitter' is not generic

As I follow along with a tutorial, I've come across the use of EventEmitter. The code snippet provided in the tutorial is as follows: @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); However, my Visual ...

How would you define 'Idiomatic' in the context of Idiomatic Javascript?

During his initial discussion on TypeScript, Anders repeatedly mentions the term 'idiomatic javascript'. Can you clarify the specific definition of idiomatic in this context? I've attempted to research this on Wikipedia and Stack Overflow, ...

Creating Angular unit test modules

When it comes to creating unit test cases for an Angular app, the application functionality is typically divided into modules based on the requirements. In order to avoid the need for repeated imports in component files, the necessary components, modules, ...

Leveraging the keyof keyword to access a specific property within a type

I have a variety of types that I need to work with. For example: type Type = { prop1: number; prop2: string; prop3: someOtherType } type Props = keyof Type I am aware that using an "indexed access type" allows me to extract the type of propN, ...

Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where t ...

In Typescript, it mandates that a string value must be one of the values within the object

There is a constant declaration mentioned below: export const Actions = { VIEW: 'view', EDIT: 'edit', }; Imagine there's a function like this: // Ensuring that the action variable below is always a string with value either ...

The npm warning indicates that there is tarball data for @angular/compiler version ~8.2.4

Whenever I try to create a project in Angular, I encounter this error. Can someone please advise me on how to fix it? I keep getting the npm WARN tarball tarball data for @angular/compiler@~8.2.4 error message. ...

Having trouble with React throwing a SyntaxError for an unexpected token?

Error message: Syntax error: D:/file/repo/webpage/react_demo/src/App.js: Unexpected token (34:5) 32 | 33 | return ( > 34 <> | ^ 35 <div className="status">{status}</div> 36 <div className=&quo ...

Encountering an issue while attempting to retrieve a key from an Object within an Observable using async functionality

I have a seemingly basic and simple Object that I retrieve using Rx and would like to display a portion of it on screen. I removed all HTML and simply added {{ structure$ | async | json }}, with structure$ being the name of the Observable in my component, ...

Troubleshooting: Angular2 fails to send HTTP GET requests

There seems to be an issue with the code provided in (A) where it fails to send its HTTP request when `test()` is called. In contrast, the similar code in (B) functions properly. Do you have any insights into what might be causing this problem? I can confi ...

Encountering an error when invoking a web API controller from a service in Angular 2

I am currently following an Angular quick start tutorial that focuses on the Hero tutorial provided on the Angular2 website. The tutorial runs smoothly for me as it binds static array data and allows for CRUD operations. However, my goal now is to understa ...