Stop certain sections of Typescript code from being compiled

In my scenario, I have two classes: class A and class B. Class B extends class A. The issue arises when we consider a method in both classes. Class A has a method that accepts AProperties enum as its first argument. However, class B has a similar method that accepts either AProperties or BProperties enum as its first argument.

enum AProperties {
    X,
    Y
}

enum BProperties {
    Z,
    W
}

class A {
    setProperty(property: AProperties, value: number) {

    }
}

class B extends A {
    setProperty(property: AProperties | BProperties, value: number) {

    }
}

It seems redundant to have the setProperty method in class B, since it is identical to the one in class A. This method is only added for the TypeScript editor to recognize that it can accept both AProperties and BProperties. However, when the code is compiled to JavaScript, having setProperty in class B serves no purpose.

Is there a way to prevent this redundant method from being included in the JavaScript compilation? Perhaps adding a comment before the method could effectively address this issue.

Answer №1

One way to work around the issue of skipping code without commenting it out in the compiler is by structuring your code in a way that avoids the need to implement the method in the child class. Take a look at this example:

enum AProperties {
    X,
    Y
}

enum BProperties {
    Z,
    W
}

class Base<T> {
    setProperty(property: T, value: number) {
        // ...
    }
}

class A extends Base<AProperties> {}

class B extends Base<AProperties | BProperties> {}

In this approach, a separate class (Base) is introduced to contain the implementation of setProperty, which is then extended by A and B to specify the type of the property enum.

You can also explore a potential feature that suggests default generic types to simplify the code, like this:

class A<T = AProperties> {
    setProperty(property: T, value: number) {}
}

class B extends Base<AProperties | BProperties> {}

However, until this feature is implemented, the Base class will still be required.


Edit

Alternatively, here's another solution that eliminates the need for the extra class (Base):

interface Base<T> {
    setProperty(property: T, value: number);
}

class A implements Base<AProperties> {
    setProperty(property: AProperties, value: number) {
        // ...
    }
}

class B implements Base<AProperties | BProperties> {
    setProperty: (property: AProperties | BProperties, value: number) => void;
}

let a = new A();
a.setProperty(AProperties.X, 4);

let b = new B();
b.setProperty(AProperties.X, 4);
b.setProperty(BProperties.W, 4);

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

Deleting a button from a list item or array in Angular 12

Having some trouble removing a list item with the click button, I've tried a few options but nothing seems to be working. Can anyone offer assistance? I need to remove a list item from my users array when clicked. Below is the Typescript code and cor ...

What is the proper way to define a tuple type with a specific size N for the vector class in C++?

I am seeking to create a tuple type with a fixed size N, allowing for functionality such as: let tuple: Tuple<string, 2> = ["a","b"] In this scenario, "number" represents the type T, and "2" denotes the size N. Subsequently, I ai ...

Guide on incorporating external .d.ts files for a module

I'm currently delving into the process of utilizing an external .d.ts file that is not included in the module. My intention is to make use of xlsx, which lacks its own type definitions, and instead incorporate them from the package @types/xlsx. Afte ...

Switching between PascalCase and camelCase in TypeScript leads to unexpected behavior

Currently, I am in the process of transitioning a C# desktop application to an Angular/TypeScript web application. In the C# application, all class properties are named using PascalCase. Therefore, I decided to maintain this naming convention in the TypeS ...

Using custom hooks in JSX triggers a TypeScript error when the returned component is accessed

i just created a custom hook // useDropdown.ts function useDropdown(defaultState: number, options: number[]) { const [state, setState] = useState(defaultState); function Dropdown({ name }: { name: string }) { return ( <> <sel ...

Tips on changing the date format in Typescript to the desired format

My date string reads as 2016-09-19T18:10:31+0100. Here's what I'm doing: let dateString:string = 2016-09-19T18:10:31+0100; let newDateString:Date = new Date(dateString); The output I'm currently getting is Tue Sep 19 2016 18:10:31 GMT+0530 ...

Semantic-ui-react cannot be located by Docker

I am a beginner when it comes to docker and I'm looking to create a React app, specifically using TypeScript, inside a docker container. In order to do this, I need to incorporate semantic-ui-react into my project. I followed the instructions provide ...

What is the best way to utilize the next-env.d.ts file within Next.js?

In my Next.js TypeScript project, I came across a file named next-env.d.ts. This got me thinking about how I can declare enums that would be accessible across all my Next.js files. Can you guide me on how to achieve this and use the enums throughout my p ...

Cannot perform table inserts or creates with NestJS Sequelize functionality

I am currently in the process of setting up a small web server with a MySQL database. To achieve this, I am utilizing NestJs along with Sequelize. However, as I am still in the learning phase, I seem to be encountering an error: Within my database, I have ...

Go through a collection of Observables and store the outcome of each Observable in an array

As a newcomer to Angular and RxJS, I am facing a challenge with handling social posts. For each post, I need to make a server call to retrieve the users who reacted to that post. The diagram linked below illustrates the process (the grey arrows represent r ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

Can a constant be utilized as the property name within routerLink when specifying queryParams?

I am currently trying to update the current page by modifying or adding the query parameter "categoryId". When I attempt: <a [routerLink]="" [queryParams]="{ categoryId: category!.id }" queryParamsHandling="mer ...

Issue encountered: "ERROR TypeError: Upon attempting to patchValue in ngOnInit(), the property 'form' is undefined."

Can someone help me figure out how to use the patchValue method in the ngOnInit() function? I'm trying to populate a HTML select dropdown with a value from a link, but it's not working as expected. Note: onTest() works perfectly when called sepa ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Angular 2: Utilize the select event to fetch and return the selected item

How can I pass an item on change event? Currently, my code looks like this: <select #sel (change)="select.emit(sel.value.url)"> <option *ngFor="let item of selectlist"> {{item.description}} </option> &l ...

Issue with custom HTML5 video progress bar not syncing with video playback

Currently, I am working on a project using React with Typescript. I have implemented an HTML5 element range for a seek bar in the video player. The issue I am facing is that although the seek bar works correctly when manually dragged, it does not update as ...

Generate user-customized UI components from uploaded templates in real-time

Summary: Seeking a solution to dynamically generate UI pages using user-provided templates that can be utilized for both front-end and back-end development across various use cases. Ensuring the summary is at the top, I am uncertain if this question has b ...

Checking to see if the prop 'isChecked' has been modified

I'm currently facing a challenge with testing whether a class's prop value changes after clicking the switcher. Below is the component class I am working with: import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core&a ...

Why do the async functions appear to be uncovered branches in the Jest/Istanbul coverage report?

I am encountering an issue throughout my application: When running Jest test coverage script with Istanbul, I am getting a "branch not covered" message specifically on the async function part of my well covered function. What does this message mean and how ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...