Function Overloads
TypeScript gives you the ability to provide more than one type signature to the same function.
type callback = (result: number) => void;
function asyncAdd(a: number, b: number): Promise<number>;
function asyncAdd(a: number, b: number, fn: callback): void;
function asyncAdd(a: number, b: number, fn?: callback) {
const result = a + b;
if (fn) return fn(result);
else return Promise.resolve(result);
}
Your Mission
We're going to to make an add
function that works with partial application. You can use this playground.
add(2, 2); // returns 4
add(2); // returns a function that accepts the second number
const addTwo = add(2);
addTwo(3); // returns 5
In case this is somewhat unfamiliar to you, this is what it might look like in JavaScript.
function add(a, b) {
if (b === undefined) return (b) => a + b;
return a + b;
}
(You can take peek at the solution here.)