An unexpected error occurs when attempting to invoke the arrow function of a child class within an abstract parent class in Typescript

Here is a snippet of code that I'm working on. In my child class, I need to use an arrow function called hello().

When I try calling the.greeting() in the parent class constructor, I encounter an error:

index.ts:29 Uncaught TypeError: this.hello is not a function at Child.greeting ...

The strange thing is that the error disappears when I switch from using a regular function to an arrow function.

I am puzzled by this issue and would appreciate any insights or solutions you may have.

abstract class Parent{
    constructor(){
      this.greeting();
    }

    abstract hello();

    greeting(){
        this.hello();
    }
}


class Child extends Parent{
  hello = ()=>{
        console.log('hello there');
    }
}

const child = new Child();

Answer №1

The functionality of the hello property in the Child class is achieved by the programming language adding a constructor to the Child class that looks like this:

constructor() {
  this.hello = () => ...
}

The Child constructor does not execute until the Parent constructor has completed its execution. Therefore, at the point when the Parent constructor is running, the hello property has not yet been assigned, causing an error. (Some languages prevent calling virtual methods from within a base class constructor for similar reasons.)

(What is the reason behind making hello an arrow function?)

Fixing this issue can be a bit tricky. If you want to be able to call the hello method from the Parent constructor, you cannot initially define it as an arrow function.

Possibly, there is a need for hello to act as both a regular and separable function (i.e., being called as a plain method without functioning as a function). In that case, you could bind it when required by using child.hello.bind(child) when necessary.

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

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

Generics in Typescript interfaces

I'm trying to grasp the meaning of T = {} within this TypeScript interface. I've searched for documentation on this usage but haven't found anything specific. How does it differ from simply using T? interface CustomProps<T = {}> { ...

"Upon refreshing the browser, an Angular map loses its positioning and appears blank

I have implemented a LeafLet map in my Laravel 9 system, which is functioning properly with some exceptions. Here's how it looks like: https://i.stack.imgur.com/kcuVr.jpg The code in the controller (CompetitionsMapController.php) is as follows: ...

Identifying imports from a barrel file (index.ts) using code analysis

Can anyone help me understand how the Typescript compiler works? I am trying to write a script that will parse each typescript file, search for import declarations, and if an import declaration is using a barrel-file script, it should display a message. Af ...

Switch up a JSON string using JavaScript

I received a JS string through an AJAX API call containing data like this: {"Task":"Hours per Day","Slep":22,"Work":25,"Watch TV":15,"Commute":4,"Eat":7,"Bathroom":17} My goal ...

What could be causing the isAuthenticated function to return false in the local strategy of passport.js even after a user

Here is the code I am using for authentication with passport-local strategy: routes.post("/login", passport.authenticate("local"), (req, res) => { res.json(req.user); }); function ensureAuth(req, res, next) { console.log(req.isAuthenticated()) ...

Displaying foreign exchange rates using Shield UI Chart

In my quest to access and display forex data, I have stumbled upon the incredible Shield UI Chart. After some experimentation, I successfully mastered the art of implementing ajax: $.ajax({ url: 'http://api.apirates.com/jsonp/update', dataTy ...

Leveraging an external Typescript function within Angular's HTML markup

I have a TypeScript utility class called myUtils.ts in the following format: export class MyUtils { static doSomething(input: string) { // perform some action } } To utilize this method in my component's HTML, I have imported the class into m ...

JavaScript-powered dynamic dropdown form

I need help creating a dynamic drop-down form using JavaScript. The idea is to allow users to select the type of question they want to ask and then provide the necessary information based on their selection. For example, if they choose "Multiple Choice", t ...

What is the process for inserting a scroll bar within a div element?

   I have recently created a webpage using some divs, along with a bit of CSS and JavaScript. I am struggling to figure out how to add a scrollbar to one of my divs. The code is not overly complex, as it includes both CSS and JavaScript. <html> & ...

Utilizing Angularjs for dynamic data binding in HTML attributes and style declarations

Can someone help me figure out how to use an AngularJS model as the value for an HTML attribute? For example: <div ng-controller="deviceWidth" width={{width}}> </div> Additionally, how can I achieve this within <style> markup? Where ...

When the Angular UI Bootstrap typeahead ng-model is cleared, it displays as null

The filter is performing admirably, however, after deleting the entered text, the {{filterlist.name}} displays null. This leads to the tables appearing empty due to the presence of null. Check out the demo here: https://plnkr.co/edit/1QVdctw1hr4ggJOtFHUZ? ...

What is the best way to retrieve data from within a for loop in javascript?

Seeking assistance in Typescript (javascript) to ensure that the code inside the for loop completes execution before returning I have a text box where users input strings, and I'm searching for numbers following '#'. I've created a fun ...

Possible solution to address the issue: xhr.js:178 encountered a 403 error when attempting to access https://www.googleapis.com/youtube/v3/search?q=Tesla

Encountering this console error: xhr.js:178 GET https://www.googleapis.com/youtube/v3/search?q=river 403 A specific component was designed to utilize the API at a later point: const KEY = "mykeyas23d2sdffa12sasd12dfasdfasdfasdf"; export default ...

Removing the Login button from the layout page after the user has logged in can be achieved by

I am currently developing an MVC application in Visual Studio 2012. Within my layout page, there is a login button that I would like to hide after the user successfully logs in. Despite my attempts, the method I am using doesn't seem to be working. Ca ...

Having trouble with the mouse trail code on codepen.io

I am currently attempting to integrate this specific CodePen sample into a Hugo template called Somrat Theme. I'm facing challenges in deciding where to place the HTML file; only the 'no cursor' section should go into style.css, and I need ...

Issue with React-Toastify not displaying on the screen

After updating from React-Toastify version 7.0.3 to 9.0.3, I encountered an issue where notifications are not rendering at all. Here are the steps I followed: yarn add [email protected] Modified Notification file import React from "react" ...

React components do not re-render when the context value changes

The issue with React not re-rendering when the context value changes persists I am using tailwindcss, React(v18.2.0), and vite(3.2.4). I have already attempted i want that clicking on TodoItem should change the completed value in the todo using React con ...

Managing multiple properties linked to a main component array in VueJS

I am facing a challenge with a list of components that I would like to make editable and replicate the state to the parent component. The list component is defined as: Vue.component("shortcuts", { props: { shortcuts: Array }, template: '... ...

AngularJS: updating a module

I recently started learning AngularJS and I need some guidance on how to refresh the data in a table within a module (specifically, a list of names and post codes). Below is the script where I am trying to reload the JSON file upon clicking a button: < ...