Suppose you have a function, written in TypeScript, that is fine and complete. Now you want to write a function that works like that one but with just some slightly more parameters and other differences. It's not too different from a decorator function.
Extending the list of parameters
Let's imagine that you already have this function:
type Operation = "sum" | "sub" | "mul" | "div"
function calculator(a: number, b: number, op: Operation) {
if (op === "sum") return a + b
if (op === "sub") return a - b
if (op === "mul") return a * b
if (op === "div") return a / b
throw new Error(op)
}
And this could, for the sake of argument, be in a different file and/or possibly outside your control. What you now want to do is write a new function that takes those same arguments, plus one more. And importantly, you don't want to have to spell out all the arguments one more time.
First, the WRONG way to solve this:
import { calculator } from './calculator' // The code in the snippet above
type Operation = "sum" | "sub" | "mul" | "div"
function doubleCalculator(a: number, b: number, op: Operation, c: number) {
return calculator(calculator(a, b, op), c, op)
}
console.log(calculator(1, 2, "sum")) // 3
console.log(doubleCalculator(1, 2, "sum", 10)) // 13
Technically, it works, but you had to repeat the calculator
function's signature.