Today, I was learning aboout TypeScript overloads, and I saw something in TypeScript's documentation like so:
function fn(x: string): Moment;
function fn(x: number): Moment;
function fn(x: number | string) {
// When written with separate overloads, incorrectly an error
// When written with union types, correctly OK
return moment().utcOffset(x);
}
Here's the reference: Dos and Don'ts
What does it mean by incorrectly an error? I did executed this piece of code on my machine, it didn't throw error. Who can explain this for me? Thanks!
Today, I was learning aboout TypeScript overloads, and I saw something in TypeScript's documentation like so:
function fn(x: string): Moment;
function fn(x: number): Moment;
function fn(x: number | string) {
// When written with separate overloads, incorrectly an error
// When written with union types, correctly OK
return moment().utcOffset(x);
}
Here's the reference: Dos and Don'ts
What does it mean by incorrectly an error? I did executed this piece of code on my machine, it didn't throw error. Who can explain this for me? Thanks!
Share Improve this question asked Jan 19 at 3:33 Devin JohwDevin Johw 1338 bronze badges 2- 2 "It didn't throw error" What do you mean? Runtime? Compile time? If I look at that doc and put the code in a minimal reproducible example (which you should really do for us, by the way, a link to "Dos and Don'ts" doesn't count), I get code which looks like this playground link and sure enough there is indeed an error. Do you not see that error in your environment? If not, what are you doing? Please edit to give us a minimal reproducible example so we can all be on the same page about the behavior you're describing. – jcalz Commented Jan 19 at 3:56
- I get it, your comment helps. – Devin Johw Commented Jan 19 at 4:23
1 Answer
Reset to default 1The TypeScript documentation mentions "incorrectly an error" because of how TypeScript checks the implementation of overloads.
- The first two lines define how the function can be called.
- The third line implements the function, which must handle all the overloads correctly.
TypeScript checks if the implementation matches all overloads.
If TypeScript can't confirm that moment().utcOffset(x)
supports both number
and string
, it might incorrectly throw an error.