Exploring TypeScript by defining a parent class with identical methods but varying constructors

Here is the code snippet I am currently working on:

class X {
    constructor(
        private _x: number,
    ) {}

    method1() {}
    method2() {}
}

class Y {
    constructor(
        private _y: number,
    ) {}

    method1() {}
    method2() {}
}

class Z {
    constructor(
        private _z: number,
    ) {}

    method1() {}
    method2() {}
}

let itemList = [new X(1), new Y(2), new Z(3)];
itemList.forEach((item: any) => {
    item.method1();
})
 

I have these three classes (X, Y, and Z) each with different constructors and methods that share the same name.

How can I specify a specific type other than any in TypeScript to ensure that method1 is recognized by the compiler?

Answer №1

Essentially, the solution was hinted at in the comments, but since the answer wasn't provided, here's the most direct approach: creating a new type.

class A {
    constructor(
        private _a: number,
    ) {}

    public commonMethod() {
      console.log("A")
    }
}

class B {
    constructor(
        private _b: number,
    ) {}

    public commonMethod() {
      console.log("B")
    }
}

class C {
    constructor(
        private _c: number,
    ) {}

    public commonMethod() {
      console.log("C")
    }
}

type letters = A | B | C

let list = [new A(1), new B(2), new C(3)];
list.forEach((element: letters) => {
    element.commonMethod();
})
 

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

Distinguishing between Javascript Array Objects and Array-Like Objects: An Elucidation

While attempting to convert an array-like object into a string using JSON.stringify, I discovered that the function was not working correctly when the array-like object was declared as an array object. For more clarity, please refer to the following --> ...

Exploring JSON Array Data and Its Sub-Properties in React

I have a JSON array containing personal data that I want to access from my React app. This JSON file is already included in my React application. { "person": [ { "id": "userId", "sellerImage": "https://i.pravatar.cc/300", ...

An error is triggered by the EyeDropper API stating that 'EyeDropper' has not been defined

I am trying to utilize EyeDropper for an eyedropper function in my project that uses Vue2 + Ts. Here is the code snippet: <div v-if="haveEyeDropper" @click="handleClickPick" > <i class="iconfont icon-xiguan"> ...

Angular 14: Enhance Your User Experience with Dynamic Angular Material Table Row Management

My inquiry: I have encountered an issue with the Angular material table. After installing and setting up my first table, I created a function to delete the last row. However, the table is not refreshing as expected. It only updates when I make a site chang ...

How to modify a specific item in a React list using TypeScript

Currently, I am working on a React project with Express as the backend. I have a list of items that can be edited or deleted. However, when I try to display the ID of a specific element in the console after clicking the edit button, it appears blank. I ha ...

Spacing Problem with Title Tooltips

After using the padEnd method to ensure equal spacing for the string and binding in the title, I noticed that the console displayed the string perfectly aligned with spaces, but the binded title appeared different. Is it possible for the title to support s ...

tsconfig.json respects the baseUrl for absolute imports inconsistently

While using create-react-app, I have noticed that absolute imports work in some files but not in others. Directory Layout . +-- tsconfig.js +-- package.json +-- src | +-- components | | +-- ui | | | +-- Button | | | | +-- Button.tsx | ...

Is passing data through interfaces a suitable practice in TypeScript?

In my project, I have come across instances where an interface is being utilized instead of a class. For example: function check(car: ICar) { //perform some actions } this.check({mark: "Toyota", colour: "blue"}); Is it acceptable to continue using inter ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

The Azure function application's automatic reload feature does not function properly with the v4 model

Struggling to get Azure Function to recognize and incorporate changes in source code. I have set up a launch task to initiate the local server and run an npm script with tsc -w in watch mode. While I can see the modifications reflected in the /dist folder ...

Implementing JavaScript Code in TypeScript

Every JavaScript code should also be valid in TypeScript, but when attempting to run the following code snippet below, an error is triggered. Could someone convert this JavaScript code into TypeScript? Error: 20:9 - TS2531 Error: Object is possibly 'z ...

Enhance your ReactJS form with added values

I am interested in creating multiple forms and consolidating all the input values into a single variable with distinct objects export default function FormView() { const [values, setValues] = useState<ResumeViewType>({ contact: { name: &a ...

Having trouble obtaining React 15.6.1 type definitions: "ERROR: Repository not found."

Trying to set up the type definitions for React 15.6.1, but encountering an error: $ npm install --save @types/react npm ERR! git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88efe1fcc8efe1fce0fdeaa6ebe7e5">[email&# ...

Using Conditional Types in Supabase Query results in the TypeScript error, "Type is incompatible with type 'never'."

Query I have encountered a TypeScript issue while working on a Next.js project with Supabase as the backend. To handle responses from Supabase queries, I created some helper types, but I'm stuck on resolving this problem. Helper Types Overview: Belo ...

What is the best way to verify if the text values of a collection of DOM-nodes in an array match a specific string

My objective is to validate if all names in an array are equal to e2e. I have a set of objects generated using protractor's element.all(by.css(...). The next step involves confirming if any element within the array has a text value that differs from m ...

Is there a way in typescript to transform empty strings into null values?

As a newcomer to TypeScript, I have been exploring it for some time now. I am working with two interfaces, one is fetching data from a database that I do not have control over and cannot guarantee the values returned are as expected. // Retrieved from the ...

What are the methods used in TypeScript to implement features that are not available in JavaScript, despite TypeScript ultimately being compiled to JavaScript?

After transitioning from JavaScript to TypeScript, I discovered that TypeScript offers many features not found in JS, such as types. However, TypeScript is ultimately compiled down to JavaScript. How is it possible for a language like TypeScript to achie ...

Looking to develop a dynamic password verification form control?

I am in the process of developing a material password confirmation component that can be seamlessly integrated with Angular Reactive Forms. This will allow the same component to be utilized in both Registration and Password Reset forms. If you would like ...

Variable storing an array of strings in TypeScript with React JS

Currently, I am facing an issue with my array object declaration in relation to the declared interface. I am puzzled as to why I am receiving errors for all my properties. Can someone help me understand why I am getting the following errors? [0] (10,5): ...

Is there a way to deactivate keyup loopback in Angular 2?

Here is my form: <div *ngIf="formLabel" style="padding: 0 16px"> <md-input [(ngModel)]="label.Name" placeholder="Label name" style="width: 100%"> </md-input> </div> <md-list-item *ngFor="l ...