Expanding a class in Typescript by adding a function with the same name but varying properties and types

class A {

  play(a: string): string{
    return a;
  }

}

class B extends A {

  play(c: string, b: number): string{
    return c + ' ' + b.toString();
  }

}

let x = new A();
console.log(x.play('John'));

let y = new B();
console.log(y.play('Doe', 1985));

I encountered an error when compiling the code:

Property 'play' in type 'B' is not assignable to the same property in base type 'A'. Type '(a: string, b: number) => string' is not assignable to type '(a: string) => string'

Any suggestions for addressing this issue?

Answer №1

One key aspect of inheritance is the ability to treat any subclass just like its superclass. This means that the public interface of parent class instances must be preserved in child class instances, ensuring type safety when using a child class as if it were a parent class instance.

However, altering the interface breaks this contract, which is not permissible.

For instance, any subclass of A should be passable to this function:

function getGame(instance: A) {
     return instance.game('name')
}

If an instance of class B is passed to this function, it will fail because the game method requires two arguments for class B, but only one for class A.

As a result, Typescript does not permit this behavior.

There are various ways to address this issue, but here are two suggestions.


Solution 1:

Make the second parameter optional.

class B extends A {
  game(a: string, b?: number): string{
    return a + ' ' + b?.toString();
  }
}

By making the second parameter optional, you can safely call instances of class B with only one argument. Thus, treating a B instance as an A instance allows calling the game method with just one argument.

When certain that it is a B instance, the second argument can still be provided.

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

Inform the Angular2 Component regarding the creation of DOM elements that are placed outside of the

The Challenge In my Angular2 project, I am using Swiper carousel and building it with Webpack. However, Angular2 adds random attributes like _ngcontent-pmm-6 to all elements in a component. Swiper generates pagination elements dynamically, outside of Ang ...

TSLint is unable to locate a custom module containing a custom d.ts file

I've been searching for a solution to this issue, but haven't found a definitive answer yet. My current challenge involves using the suncalc module with TypeScript. Since it doesn't come with its own typing file, I created one and saved it ...

Combine array elements in Angular/Javascript based on a certain condition

Is there a way to combine elements from two arrays while avoiding duplicates? array = [ {id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'} ]; The desired output is: result = [{id: ...

Error encountered when updating Angular CLI

I am currently attempting to update my Angular project from version 4 to version 6. After numerous failed attempts to upgrade, I decided to uninstall and reinstall the Angular CLI using 'npm uninstall -g angular-cli' followed by a reinstallation. ...

Unable to loop through the Array

let Users = [ { name: 'John', id: '1', jp: 'USA' }, { name: 'Jane', id: '2', jp: 'Japan' }, ]; export function DisplayUsers(usersList) { return ( <div> {usersList?.map((user ...

My goal is to intentionally trigger an eslint error when importing a file from index.ts

Is there a way to enforce importing components from index.ts within the src/components directory using eslint rules or plugins? // index.ts (src/components/Forms) export { Input } from './Input'; export { CheckBox } from './CheckBox'; ...

The wildcard syntax for importing statements in Angular 2

I created multiple classes in a single file with the following structure file: myclasses.ts export class Class1 {....} export class Class2 {....} export class Class3 {....} Now I am attempting to import all of them using a wildcard like this import {*} ...

Encountering issue with FullCalendar and Angular 11: Error reading property '__k' of null

I am currently utilizing the Full Calendar plugin with Angular 11 but have encountered an error message stating "Cannot read property '__k' of null". It appears to be occurring when the calendar.render() function is called, and I'm strugglin ...

Is there a way to run the mediapipe face detection codepen.io demo on my laptop?

After successfully running the mediapipe face detection demo from Mediapipe official website, I wanted to replicate it on my laptop. To achieve this, I created an 'index.html' file and meticulously transferred the code from the CodePen demo page ...

Retrieve the output of forkJoin subscription in Angular 6 using rxJs 6

A Straightforward Example: const tasks = []; for (let i = 0; i < this.initialData.length; i++) { tasks.push( this.taskService.getDetails(this.id1[i], this.id2[i]) }; combineLatest(...tasks).subscribe(taskGroup => { console.log(task ...

Navigate back to the main page using a tab

Is there a way to navigate back to the rootPage that is defined in the appComponent when using tabs? I have found that the setRoot method does not function as I anticipated. When used on a Tab page, the navigation stack is not cleared. Instead of the navig ...

The srcSet functionality in the Image component seems to be malfunctioning in the next.js framework, as it is failing to display

Check out my Next.js code snippet below: import React from "react"; import style from "@/styles/Home.module.css"; import Image from "next/image"; function index() { return ( <> <div className="contai ...

I'm experiencing difficulty in scrolling on my Nextjs web application

Currently, I am facing an issue with my portfolio webpage which is divided into 3 main components - Hero, About, and Portfolio. The layout structure is as follows: export default function RootLayout({ children, }: { children: React.ReactNode }) { ret ...

What is the method for implementing a custom layout for the items within a Select component?

I want to customize the options of a Select component by adding HTML elements. Here is an example: <mat-select [(ngModel)]="items"> <mat-option *ngFor="let item of ($items | async)" [value]="item.id"> <span>{{item.name}}</span&g ...

What is the process to verify a password?

Hey everyone! I've successfully implemented control forms in my login.component.ts for handling email and password input. Now, I want to add these controls to my register.component.ts as well. Specifically, how can I implement controls for the passwor ...

Trigger the Angular Dragula DropModel Event exclusively from left to right direction

In my application, I have set up two columns using dragula where I can easily drag and drop elements. <div class="taskboard-cards" [dragula]='"task-group"' [(dragulaModel)]="format"> <div class="tas ...

Guide to including spinner in React JS with TypeScript

I need help with adding a spinner to a React component. The issue I'm facing is that the spinner does not disappear after fetching data from an API. Can someone please point out what I am doing wrong? Here is the code snippet: import React, { useSta ...

The parameter 'EventTypes' cannot be assigned to a type of string

I am working on enhancing the functionality of the function provided below by adding types to it, clickEvent(event:Event) { this.event = event } The HTML Code: <a [href]="href" [target]="target" (click)="clickEvent('text')"></ ...

Angular Material: Enhanced search input with a universal clear button

After searching for a cross-browser search control with a clear button similar to HTML5, I found the solution rendered by Chrome: <input type="search> The code that gave me the most relevant results can be found here. I used the standard sample w ...

Images in Angular Firebase causing scroll problems in Chrome

In regard to Angular 6, a common issue arises with slow image loading specifically in Chrome, not other browsers. The project utilizes Firebase and the snapshotchange method to fetch images for the Angular project. Image URLs used are like this: . The iss ...