Can a subclass or interface delete an inherited field or method from its parent class?

Here's a scenario:

interface A {
  a: number;
  x: any;
}

interface B extends A {
  b: number;
}

interface C {
  a: number;
  b: number;
}

Can we make B equal to C (excluding the x field but still extending A)? If it is possible, then how can we achieve it?

Answer №1

In TypeScript, removing an inherited field or method from an interface is not possible.

However, you can overcome this limitation by reengineering interfaces:

  1. Extract a base interface

    interface BaseA {
      a: number;
    }
    
    interface A extends Base A {
      x: any;
    }
    
    interface B extends A {
      b: number;
    }
    
    interface C extends BaseA {
      b: number;
    }
    

Both C and B can be cast to BaseA.

  1. Utilize optional fields

    interface A {
      a: number;
      x?: any;
    }
    
    interface B extends A {
      b: number;
    }
    
    interface C extends A {
      b: number;
    }
    

There may be other approaches depending on the specific context of the task.

Answer №2

If you're looking for a workaround to handle the deletion of child interface members, here's a clever solution:

interface Base {
  a: number;
  x?: any;
}

interface Child extends Base {
  x?: undefined;
}

By using this approach, the x field either shouldn't exist at all, or if it does, it must be explicitly set to undefined. This effectively eliminates the field in most cases, unless you specifically need to access class members or perform similar operations.

Answer №3

To achieve this, you can utilize typescripts omit type-keys feature. It's important to note that in typescript, you have the ability to extend multiple interfaces simultaneously.

Typescript omit:

Creates a type by selecting all properties from Type and then removing Keys (string literal or union of string literals).

Using the example provided:

interface A {
  a: number;
  x: any;
}

interface B extends A {
  b: number;
}

interface C extends Omit<A, 'x'>, Omit<B, 'x'> {}

The result:

interface C {
  a: number;
  b: number;
}

Try out the working Typescript Playground demo here

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

Creating an extended class with mandatory properties

In order to streamline code sharing between two classes that overlap, I decided to create a new class called Common. For one of the subclasses, I needed all the properties from the Common class to be required. My initial thought was to utilize the Require ...

Tips for incorporating asynchronous page components as a child element in next.js?

Utilizing the latest functionality in next.js for server-side rendering, I am converting my component to be async as per the documentation. Here is a simple example of my page component: export default async function Home() { const res = await fetch( ...

Following a series of Observables in Angular 2+ in a sequential order

Apologies if this question has been answered elsewhere, I attempted to search for it but I'm not exactly sure what I should be looking for. Imagine I have this complex object: userRequest: { id: number, subject: string, ... orderIds: ...

Guide on setting up next-auth for external API login in a Next.js 13 app directory

Hey there, I'm currently working on setting up a login system with next-auth in Next.js 13 using appDir: true. The version of Next.js I am using is 13.3.0, but after going through the documentation, I must admit that I'm struggling to fully grasp ...

Managing TypeScript objects

Just starting out with TypeScript and feeling a bit lost. The data I receive from my BackEnd looks like this: { "A": [ { "fieldA": 0, "fieldB": "A", "fieldC": ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

https://i.sstatic.net/q4x3m.png Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error ...

Error encountered when initializing a variable within the constructor of a TypeScript file in Angular 4

This is the content of my app.component.html file PL Auth Username: Password : Generate OTP Enter OTP : Login This is the code in my app.component.ts file import { Component, OnInit } from '@angular/core' ...

Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig a ...

Metronome in TypeScript

I am currently working on developing a metronome using Typescript within the Angular 2 framework. Many thanks to @Nitzan-Tomer for assisting me with the foundational concepts, as discussed in this Stack Overflow post: Typescript Loop with Delay. My curren ...

What is the best method to find a matching property in one array from another?

I am working with two arrays in TypeScript. The first one is a products array containing objects with product names and IDs, like this: const products = [ { product: 'prod_aaa', name: 'Starter' }, { product: 'prod_bbb&apos ...

Can the inclusion of a type guard function impact the overall performance of the application?

const typeGuard = (param: any): param is SomeType => { return ( !!param && typeof param === "object" && param.someProperty1 !== null && param.someProperty2 === null ) } If a type guard function similar to the code above is exe ...

Add a hyperlink within a button element

I am looking to add a route to my reusable 'button' component in order to navigate to another page. I attempted using the <Link> </Link> tags, but it affected my CSS and caused the 'button' to appear small. The link works if ...

Ionic: Implementing a clear text field function when the ion-back-button is clicked

So I've created a feature where users can scan product barcodes using BarcodeScanner. Once the barcode is scanned, the product ID appears in a text field and is then sent to another page where an API call is made to display product details. On this pr ...

Error: The function setIsEnabled does not exist

Currently, I am in the process of merging two separate next.js projects to create a website that can utilize the Cardano wallet 'Nami'. The code for accessing the wallet functions correctly in its original project, but when transferred over, it p ...

What is the reason for sending a single file to the server?

A function called "import File" was developed to send multiple files to the server, but only one file is being received. Input: <input type="files" id="files" name="files" multiple onChange={ (e) => this.importFile(e.target.files) } ...

What is the best way to configure webpack for ng build instead of ng serve?

My .NET web application is hosted in IIS and it also hosts an Angular application. This setup requires both applications to be served on the same port by IIS, primarily because they share the same session cookie. Additionally, they are integral parts of th ...

Issue encountered when working with interface and Observable during the http parsing process

Visual Studio File Structure Error app(folder) -->employee-list(folder) -->employee-list.component.html -->employee-list.component.ts -->app.component.html -->app.component.ts -->app.module.ts -->employee.json ...

Sending asynchronous data to a child component in Angular 2

Having trouble with passing asynchronous data to a child component. I am attempting to create a dynamic form generator, but I encounter an issue when trying to fetch JSON data via an Observable and then passing it to the child component. Service: generat ...

Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

Troubleshooting Ionic 4 IonSlides slideTo and getActiveIndex functionalities encountering issues within IonTab context

I am encountering an issue with my ion slides setup on a page. Here is the code snippet: <ion-slides #schemasliderref [options]="schemaSliderOpts" (ionSlideDidChange)="slideChange()"> <ion-slide *ngFor="let schemaImage of schemaImages; let i ...