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

147
Visualizações
Overriding a method with different parameters in Typescript

While reading the method overriding part of the Typescript documentation, I came across something interesting. Normally the method of base class would not be referenced while overriding method in javascript. But it is different in typescript.

Example

class Base {
  greet() {
    console.log("Hello, world!");
  }
}

class Derived extends Base {

  /* 
  Property 'greet' in type 'Derived' is not assignable to the same   property in base type 'Base'.
  Type '(name: string) => void' is not assignable to type '() =>     void'.
  */
  greet(name: string) {
    console.log(`Hello, ${name.toUpperCase()}`);
  }
}

Actually, it can be done this way.

class Derived extends Base {
  greet(name?: string) {
    if (name === undefined) {
      super.greet();
    } else {
      console.log(`Hello, ${name.toUpperCase()}`);
    }
  }
}

But why? Is this a pattern? Do I have to do it this way when overriding method?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

"Assignable" in typescript simply means that the parameter and return types overlap.

You have these signatures:

greet(): void;
greet(name: string): void;

Since the parameter types don't overlap, typescript warns you that the signature is not assignable to the base method.

If you change the second method to greet(name?: string): void;

then the parameter types overlap (? means a parameter is optional)) and typescript doesn't need to warn you, because you need to manually check if name is available or not.

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