It appears that both @aaronlukacs and @captain-yossarian have missed the main point raised by the OP.
The main issue highlighted by the OP is that when writing this specific implementation:
async getA(alpha: number) {
const beta = alpha * 2;
console.log(beta);
}
TypeScript fails to notify that alpha
could potentially be a string as well, considering the overload signature getA(alpha: string | number)
. This means that while calling the function like this: const result = a.getA('1254s');
is valid, the line in the implementation: const beta = alpha * 2;
should ideally prompt an error.
This seems to be a limitation of TypeScript when handling overloaded functions, as hinted by a few recommendations provided in the official documentation:
The signature of the implementation is not readily visible.
When defining an overloaded function, it's advisable to declare two or more signatures before the actual implementation.
It's generally preferred to use union types for parameters instead of overloads whenever possible.
An optimized version of the OP's code in line with these suggestions would resemble something like this:
class Alpha {
getA(alpha: string): void;
getA(alpha: number): void;
getA(alpha: number | string): void {
const beta = alpha * 2;
console.log(beta);
}
}
This revised version would correctly flag an error at alpha * 2
, or alternatively, it could be simplified as follows:
class Alpha {
getA(alpha: number | string): void {
const beta = alpha * 2;
console.log(beta);
}
}
In the latter scenario, the overloading concept is completely eliminated.
It's worth noting that these two versions aren't entirely interchangeable: the first version of getA()
wouldn't accept a value of type string | number
.