I have a class definition as follows:
class Test {
a(msg: string): string;
a(msg: string, ...args: unknown[]): string | { msg: string, args: unknown[]} {
if (args) {
return { msg: msg, args: args };
}
return msg;
}
}
However, I get compilation errors if I do this:
new Test().a("test", "a", 1, 2, 3);
"Expected 1 arguments, but got 5"
How can I properly overload this method to provide different return types for the different signatures?
The function implementation is not part of all available overloads. Instead you can write:
class Test {
a(msg: string): string; // overload 1
a(msg: string, ...args: unknown[]): { msg: string, args: unknown[] } // overload2
a(msg: string, ...args: unknown[]): string | { msg: string, args: unknown[] } { // impl
// ...
}
}
new Test().a("test", "a", 1, 2, 3); // { msg: string; args: unknown[]; }
new Test().a("test") // string
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras