Use Union Types
Don’t write overloads that differ by type in only one argument position:
1 2 3 4 5 6 | /* WRONG */ interface Moment { utcOffset(): number; utcOffset(b: number): Moment; utcOffset(b: string): Moment; } |
Do use union types whenver possible:
1 2 3 4 5 | /* OK */ interface Moment { utcOffset(): number; utcOffset(b: number|string): Moment; } |
Note that we didn’t make b
optional here because the return types of the signatures differ.
Why: This is important for people who are “passing through” a value to your function:
1 2 3 4 5 6 7 | function fn(x: string): void; function fn(x: number): void; function fn(x: number|string) { // When written with separate overloads, incorrectly an error // When written with union types, correctly OK return moment().utcOffset(x); } |
Please login to continue.