Sobrecarga de funciones en TypeScript: ¿cómo declarar y usar correctamente?
¡Hola a todos! Acabo de empezar a aprender TypeScript y me encontré con un problema al intentar usar la sobrecarga de funciones. Tengo una función `format` que debe funcionar de manera diferente según el tipo de argumentos pasados:
1. Si se pasa un string y un número — formatear el string con repetición.
2. Si se pasan dos strings — concatenarlos con un separador.
3. Si se pasa solo un número — devolverlo como string con un prefijo.
Escribí este código, pero TypeScript se queja:
```typescript
function format(a: string, b: number): string;
function format(a: string, b: string): string;
function format(a: number): string;
function format(a: string | number, b?: string | number): string {
if (typeof a === 'number') {
return `ID: ${a}`;
}
if (typeof b === 'number') {
return a.repeat(b);
}
if (typeof b === 'string') {
return `${a} - ${b}`;
}
return a;
}
```
Error: `This overload signature is not compatible with its implementation signature.` Yo