Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

303
Vistas
Typescript: Calling the arrow function of a child class in an abstract parent class throws an error

Here is the simple code. I need to use arrow function hello() for reasons in the child class.

The code throws an error when I call the.greeting() in the constructor of the parent class:

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

However, the problem does not occur when I use the regular function, but I must use the arrow function.

Please tell me what the problem is and how to fix it.

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

    abstract hello();

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


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

const child = new Child();
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The way the hello property in Child works is effectively by the language adding a constructor to Child which says:

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

That Child constructor doesn't run until the Parent constructor has finished, so at the point the Parent constructor is running, hello hasn't yet been assigned. So that's why it blows up. (Some other languages prevent you from calling virtual methods from inside a base class constructor for the same reason.)

(Why do you 'need' to make hello an arrow function?)

Fixing it is a little tricksy. If you want it to be callable from the Parent constructor, you simply can't make it an arrow function immediately.

Presumably you need to use an arrow function because you sometimes want hello to work as a separable function (i.e. called as a plain method without being a function)? If so, you could simply bind it on use, by using child.hello.bind(child) when you need that.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda