Estoy tratando de crear un puente entre dos servicios con una interfaz incompatible.
ServiceType es un argumento del usuario, por lo que debe validarse durante el tiempo de ejecución.
Lo mejor que se me ocurrió es esto. Pero hay varios problemas. Tendré que crear un método similar como find en el objeto SericeByType para cada función en CampaignService | LeadService y el resultado de esa función es una unión de CampaignModel | LeadModel .
¿Hay una mejor manera de cómo hacerlo?
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);