Use Union Types
Don’t write overloads that differ by type in only one argument position:
/* WRONG */
interface Moment {
utcOffset(): number;
utcOffset(b: number): Moment;
utcOffset(b: string): Moment;
}
Do use union types whenver possible:
/* 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:
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.