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

199
Visualizações
Implement an interfaces with multiple inheritance in a Nodejs class

I tried the following way to create an interface and implement it.

class AInterface {
  constructor () {
    if (!this.methodA) {
      throw new Error('class should implement a methodA() method')
    } else if (!this.methodB) {
      throw new Error('class should implement a methodB() method')
    }
  }
}
export default AInterface

implemented that in a class by extending it. (Note that I have used ts-mixer to have multiple inheritance.

import AInterface from './AInterface'
import { Mixin } from 'ts-mixer'

class ClassA extends Mixin(AnotherClass, AInterface) {

  constructor () {
    super()
  }

  methodA () {
    return 'test'
  }

  methodB () {
    return 'test'
  }

}
export default ClassA

This will throw the error class should implement a methodA() method. Which means the check I do in the interface fails if (!this.methodA). This works fine when I remove the Mixin and extend only the interface. (class ClassA extends AInterface)

Is there a better way to do this or how can I fix this?

Node version - 14

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The problem appears to be that the constructor of AInterface does not get the right this. So it does not see the methodA or methodB.

The workaround is to avoid doing that check in the constructor.

import AInterface from "./AInterface.mjs";
import { Mixin, settings } from "ts-mixer";

settings.initFunction = "init";

class ClassA extends Mixin(AnotherClass, AInterface) {}

AInterface.js

class AInterface {
  init () {
    if (!this.methodA) {
      throw new Error('class should implement a methodA() method')
    } else if (!this.methodB) {
      throw new Error('class should implement a methodB() method')
    }
  }
}
export default AInterface

Notice the use of init() method above.

about 4 years ago · Santiago Trujillo 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