Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

302
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda