const { log } = console;
/*
┌────────────────────┐
│ function overloads │
└────────────────────┘
*/
/* -------- f() -------- */
type mixedInput = string | number;
type mixedOutput = string | boolean;
// ⭐️ should have 2+ overload signatures
function f(x: string): string;
function f(x: number): boolean;
// ⭐️ implementation signature is not visible from the outside
function f(x: mixedInput): mixedOutput {
return (typeof x === 'string') ? 'OK': true;
}
log(f('hello'), f(200)); // "OK", true
/* -------- makeDate() -------- */
// ⭐️ function overloads
function makeDate(timestamp: number): Date;
function makeDate(year: number, month: number, day: number): Date;
// ⭐️ function implementation
function makeDate(a: number, b?: number, c?: number): Date {
if (b !== undefined && c !== undefined) {
return new Date(a, b, c);
}
return new Date(a);
}
const d1 = makeDate(12345678);
const d2 = makeDate(5, 5, 5);
// const d3 = makeDate(1, 3); // ❌ no such overload signature