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

164
Visualizações
Bridge between incompatible implementations in typescript

I'm trying to create a bridge between two services with an incompatible interface.

ServiceType is an argument from the user, so it has to be validated during runtime.

The best I could think of is this. But there are several problems. I will have to create a similar method like find on the SericeByType object for each function on CampaignService | LeadService and the result from that function is a union of CampaignModel | LeadModel.

Is there a better way how to do it?

interface CampaignModel {
  id: number
}

class CampaignService {
  public async find(startId: number, limit: number): Promise<CampaignModel[]> {
    return [];
  }
}

interface LeadModel {
  id: string
}

class LeadService {
  public async find(startId: string, limit: number): Promise<LeadModel[]> {
    return [];
  }
}

type ServiceType = 'Campaign' | 'Lead'

class SericeByType {
  private readonly campaignService: CampaignService = new CampaignService();
  private readonly leadService: LeadService = new LeadService();

  public async find(type: ServiceType, startId: number | string, limit: number) {
    if (this.isCampaign(type)) {
      return this.campaignService.find(startId as number, limit);
    } else if (this.isLead(type)) {
      return this.leadService.find(startId as string, limit);
    } else {
      throw new Error();
    }
  }

  private isCampaign(type: ServiceType) {
    return type === 'Campaign';
  }

  private isLead(type: ServiceType) {
    return type === 'Lead';
  }
}

const service = new SericeByType();
service.find('Campaign', 16, 10);
service.find('Lead', 'xxxawf', 10);

Playground

about 4 years ago · Juan Pablo Isaza
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