Implementing subclass properties in TypeScript that override parent class properties

I have a base class called Parent from a library with certain properties, and a derived class Child which inherits the same properties but with different data types.

class Parent {
  propertyA: string;

  propertyB: string;
  
  propertyC: string;

  constructor() {
    this.propertyC = '';
  }
}

class Child extends Parent {
  propertyA: number;

  propertyB: number;
}

I'm attempting to change the data type of multiple properties in the parent class, but I am encountering an error ts(2416).

Type 'number' is not assignable to type 'string'.

I considered converting the Parent class into an interface and utilizing Omit<> to exclude propertyA and propertyB, however, since the class is located in a library, that approach is not feasible.

Due to the fact that the Child class will be utilized to represent existing data (such as a table with the three properties) as a generic type for functions within the firebase library (specifically the

FirebaseFirestore.CollectionReference<T>
type), I cannot use composition (PropertyParent: Parent as a Child property) or rename the properties.

Are there alternative methods to achieve this?

Answer №1

class Parent {
  propertyA: string | number;

  propertyB: string | number;
  
  propertyC: string;

  constructor() {
    this.propertyC = '';
  }
}

class Child extends Parent {
  propertyA: number;

  propertyB: number;
}

This implementation is effective because it highlights a key aspect of the Liskov substitution principle, which is discussed in depth by @T. J. Crowder with references to criticisms of that principle. One noteworthy point raised is that the principle may not fully address scenarios involving abstract or generic parent types.

In practical terms, developers can navigate to the library's source code and handle such situations by utilizing TypeScript's as keyword for casting inherited types as needed, including converting them to string if required.

Answer №2

When Parent's propertyA is a string, it follows that Child's propertyA must also be a string in accordance with the Liskov substitution principle. A Child should essentially "be" a Parent, meaning any code referencing a Child object as a Parent object should work seamlessly, expecting a string, not a number.

If this isn't the scenario in your situation, inheritance may not be the best solution. Consider using composition instead: assigning a field of type Parent to the Child.

Alternatively, allow Child to keep propertyA untouched and introduce a separate property for the number value.

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

A TypeScript interface creating a type with optional keys of various types while enforcing strict null checks

I am attempting to devise an interface in typescript that resembles the following: type MoveSpeed = "min" | "road" | "full"; interface Interval { min?: number, max?: number } interface CreepPlan { [partName: string] : Interval; move?: MoveSpe ...

Access the child component within an @ChildComponent directive in Angular

Is it possible to retrieve child components of another component? For instance, consider the following QueryList: @ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>; This QueryList will contain all instances of the SysColumns class, which ...

Trouble with Nested Routing in React Router Version 6: Route not Rendering

I'm facing issues nesting a path within another path in react-router-dom version 6. When I try to visit the nested argument's page (/blog/1), it shows up as a blank non-styled HTML page. However, when I add a child path to the root like /blog, it ...

Compilation errors plague TSC on varying systems

After successfully creating a node app in TypeScript and running it locally without any issues, I encountered compilation errors when deploying the app on Heroku: app/api/controllers/ingredient.controller.ts(3,24): error TS2307: Cannot find module & ...

I am perplexed by the CommonJS pattern, TypeScript modules, and how to effectively utilize ES6

Hey there, everyone! I'm curious if someone could provide me with a straightforward comparison of the development flow when working with CommonJS, Typescript, and ES6 in relation to the module import system (such as require(), import "xx", export), c ...

A guide to resolving the Angular 11 error of exceeding the maximum call stack size

I am currently working with 2 modules in Angular 11 CustomerModule AccountingModule I have declared certain components as widget components in these modules that are used interchangeably: CustomerModule -> CustomerBlockInfoWidget AccountingModule -&g ...

Using Angular's Hostbinding feature to toggle a button and change the background color of the

How can I change the background color of a page and all child components when a toggle button is clicked? Can this be accomplished using HostBinding in Angular? <div class="mainbody" [class.bgnight]="haveClass"> <button (click) ...

Issue with readonly is preventing the ability to alter the font color of the input

I need to change the font color of a disabled input. When it is disabled, it appears gray and I want it to be black instead. I attempted to use readonly but that did not have the desired effect, and now the input is showing [object Object]. Below is my HTM ...

Error429 was received from a GET request made to the Imgur API

Encountering a Request failed with status code 429 error from the Imgur API despite using a new Client_ID that hasn't been used before, Here is my Api.ts: const imgurClientId = process.env.NEXT_PUBLIC_Client_ID const BASE = "https://api.imgur. ...

Omit select dormant modules when building (Angular5)

Currently, I am collaborating on a project that is being implemented across various customer instances. Within the project, we have several lazy loaded modules, with most of them being utilized by all customers. However, there are certain modules that are ...

Utilize a variable from one Angular component in another by sharing it between .ts files

My issue involves dynamically adding items to a todo list and wanting to exclude certain items. The challenge lies in the fact that the list itself is located outside of the task component: Within the task.component.html file, I iterate through the list f ...

Dynamic Rendering and Retrieving Component HTML in Angular

Generate the HTML code of a component to open a new tab with an about:blank page. Reason: This method helps avoid creating HTML using string variables, such as: var html = '<div> <h3>My Template</h3> &a ...

Removing Multiple Object Properties in React: A Step-by-Step Guide

Is there a way in React to remove multiple object properties with just one line of code? I am familiar with the delete command: delete obj.property, but I have multiple object properties that need to be deleted and it would be more convenient to do this i ...

Tips and tricks for setting up a functional react select component using Material UI

Having an issue with React Select material UI where the dropdown select is not functioning properly. The popup does not open up as expected. I am looking to display react select in a modal dialog box. import MenuItem from "@mui/material/MenuItem" ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

Ensuring the accurate usage of key-value pairs in a returned object through type-checking

After generating a type definition for possible response bodies, I am looking to create a function that returns objects shaped as { code, body }, which are validated against the typing provided. My current solution looks like this: type Codes<Bodies> ...

What steps can be taken to resolve the Angular error stating that the property 'bankCode' is not found on type 'User' while attempting to bind it to ng model?

I'm encountering an issue with my application involving fetching values from MongoDB and displaying them in an Angular table. I've created a user class with properties like name and password, but I keep getting errors saying that the property doe ...

Compiling TypeScript: Using the `as` operator to convert and then destructure an array results in a compilation error, requiring an

I am currently utilizing TypeScript version 2.9.2. There is a static method in a third-party library called URI.js, which is declared as follows: joinPaths(...paths: (string | URI)[]): URI; I have a variable named urlPaths that is defined as urlPaths: s ...

Next.js: Importing from a new endpoint triggers the code execution once more

Here is a simplified example I created for this specific question. Imagine I want to maintain a server-side state. components/dummy.ts console.log('initialize array') let number: number = 0 const incrementValue: () => number = () => numbe ...

Using a BehaviorSubject in conjunction with ngIf can rearrange the placement of elements

I am facing an issue with the placement of my HTML tags. Here is a snippet from my service: public showExportCsvModal = new BehaviorSubject<boolean>(false); public showDownloadModal = new BehaviorSubject<boolean>(false); And here is how it loo ...