Issue
First, my functions:
function randIntIncl(max: number): number;
function randIntIncl(min: number, max?: number): number {
if(max === undefined) {
max = min;
min = 0;
}
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
(credit MDN)
Called like:
randIntIncl(1,9999)
I get the error:
TS2554: Expected 1 arguments, but got 2.
I'm guessing the TypeScript is matching the first overload and then erroring out. What I don't get is why it doesn't try the 2nd overload? 9999
is clearly a number, so it should match, no?
I could simply omit the first overload and everything would work peachy because I made max
optional anyway, but I put the overload there for documentation purposes. When called with one arg, that arg is the max not min as the 2nd overload suggests.
So my questions are:
- Is there a way to make this work? Did I do something wrong?
- Or is this "as designed" and I simply shouldn't create ambiguous overloads?
Solution
When you have overload signatures, the signature of the actual function definition is the "implementation signature", which doesn't count as an overload signature. If you want it to be an overload signature, you have to write it twice. See the handbook.
Answered By - Matt McCutchen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.