Bringing in functions from another class in TypeScript: A step-by-step guide

I am looking to import another class, specified by a name string (for example, 'B'), into the current class (named 'A'). The function in class B needs to be able to call a function in class A. I am seeking guidance on how to achieve this.

// index.ts

function importAll(obj, src){
    for (var key in src) obj[key] = src[key];
    return obj;
};

class A{
    function_a(){
        console.log("A_test");
    }

    call_function_b()
    {
        let classtype="./Bclass";
        // dynamically import class B 
        let B = require(classtype);
        let object_b= new B(); 
        // want to import all functions from class B to class A
        // like importAll(this, object_b);

    }
}

export let test =new A();
test.call_function_b();
//file Bclass.ts
export class B{
    function_b() {
        console.log("B_test");
    }

    function_use_a()
    {
        // function in class B needs to call function in class A
        this.function_a();
    }
}

Answer №1

It appears that you are searching for the syntax A extends B.

When using the extends keyword in class declarations or expressions, it allows you to create a class that inherits from another class.

class B {
  
  b_func() {
    console.log('b func');
  }
}

class A extends B {
  
  a_func() {
    console.log('a func');
  }
}


const a = new A();
a.b_func();

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

What could potentially occur if the sourcemap is configured to false within an Angular application?

Recently, I began learning Angular. While exploring my project files, I came across the sourcemap option in the tsconfig.json file, which is set to "sourceMap": true by default. I stumbled upon a helpful link on Stack Overflow that clarified some of my dou ...

Next.js Error: Inconsistent text content between server-rendered HTML and hydration. Unicode characters U+202F versus U+0020

Having issues with dates in Next.js development. Encountering three errors that need to be addressed: Warning: Text content did not match. Server: "Tuesday, January 24, 2023 at 11:01 AM" Client: "Tuesday, January 24, 2023 at 11:01 AM" ...

Encountering a Typescript issue when trying to access props.classes in conjunction with material-ui, react-router-dom

I could really use some help with integrating material-ui's theming with react-router-dom in a Typescript environment. I'm running into an issue where when trying to access classes.root in the render() method, I keep getting a TypeError saying &a ...

The concept of TypeScript usage within the `mui-x` DataGrid while calling the `useGridApiRef()` function

Could someone please help me understand the syntax used in this code snippet from mui/mui-x? export declare const useGridApiRef: <Api extends GridApiCommon = GridApiPro>() => React.MutableRefObject<Api>; My interpretation is that it exports ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

rxjs iterates through an array executing each item in sequential order

Is there a way to make observables wait until the previous one has completed when they are created from an array? Any help is appreciated! export class AppComponent{ arr: number[] = [5, 4, 1, 2, 3]; fetchWithObs() { from(this.arr) ...

The VSCode's intellisense for Angular Material fails to function effectively

In the midst of my project on Angular version 13, I have successfully installed Angular Material using the command below: ng add @angular/material The package has been properly included in the node_modules folder. However, when working with TypeScript ...

Checking a sequence using a list of strings

I have an array containing a list of IDs: var listId: string[] = []; var newId: boolean; for (let i in data.chunk) { listId.push(data.chunk[i].aliases[0]); } My objective is to compare a new ID with the entire list. If the new ID is found in the list ...

Stop useEffect from triggering during the first render

I'm working on implementing a debounce functionality for a custom input, but I'm facing an issue where the useEffect hook is triggered during the initial render. import { useDebouncedCallback } from "use-debounce"; interface myInputProps { ge ...

Using Typescript to assign a custom object to any object is a powerful feature

I am attempting to organize table data by utilizing the code found at https://github.com/chuvikovd/multi-column-sort. However, I am unsure of how to pass a custom object to the SortArray[T] object. The structure of my custom object is as follows: const ob ...

Choosing between Angular's Observable and Subject as a DataSourceWhen it comes

I am currently working on an Angular 7 application that utilizes Mat Tables to retrieve data from an API. I have implemented dynamic pagination values, where the pageSizeOptions value changes based on a dropdown selection when loading the grid. By default, ...

Turn off or delete certain features within an npm package

Is it possible to disable or remove unused functions in a npm library? I only need certain functions from the library and don't want others to be accessible. I want to retain the read function while disabling the write function to prevent developers ...

Controlling CSS Styles in Angular using TypeScript

Currently, I am working on an Angular project that involves dynamically populating a calendar. In addition to this, I have a range of dates and the task at hand is to modify the background for specific days within this date range. To manage dates effective ...

The issue encountered is when the data from the Angular form in the login.component.html file fails to be

I am struggling with a basic login form in my Angular project. Whenever I try to submit the form data to login.components.ts, it appears empty. Here is my login.component.html: <mat-spinner *ngIf="isLoading"></mat-spinner> & ...

Observation - Various Parties Subscribing

Exploring RxJS and Observables is a new journey for me. I recently came across this informative tutorial -> I have a question: There are three components involved: OnePage: manipulates and displays the answers Service: manages the answers SecondPag ...

Using rxjs in combination with SignalR to patiently await asynchronous notifications from background tasks

Currently, I am in the process of properly rewriting a piece of code using rxjs operators. The objective of this code is to make an http call to a webapi controller, which returns a Guid as the id of a long running background operation to be executed on th ...

Operators within an observable that perform actions after a specific duration has elapsed

Is there a way in an rxjs observable chain to perform a task with access to the current value of the observable after a specific time interval has elapsed? I'm essentially looking for a functionality akin to the tap operator, but one that triggers onl ...

Encountering issues while trying to run npm install for an Angular 7 application, specifically receiving an error stating: "Module not found: @angular-devkit/build-ng-packagr." This error is hindering

I don't have much experience with JavaScript, node, npm, Angular, etc. My expertise lies in TypeScript as I am still a beginner. However, I recently inherited an application that requires maintenance to resolve a cross-site cookie issue. As I attempt ...

Implementing Scroll Pagination in Angular 2 to Showcase Information

Recently delving into Angular2, my aim is to set up Scroll Pagination for dynamic data loading upon user scrolling. My application comprises three key Components: App.Component, Categories.Component, and Products.Component. The primary objective is to pr ...

Experimenting with Cesium using Jasmine (Angular TypeScript)

I have a TypeScript app built using Angular that incorporates Cesium: cesium-container.component.ts import { Component, ElementRef } from '@angular/core'; import { Viewer } from 'cesium'; import { SomeOtherCesiumService } from 'sr ...