Typescript API Design: Single Callable Or Multiple Callable
Acid Coder
Posted on April 1, 2022
Let's start with an example, let's say the requirement is to create a 'travel' API where it takes 'destination' and 'transportation' as arguments.
Currying is the process of transforming a function into multiple callable, but here I refer to it as a function that returns another function based on the number of parameters.
How would you design the API, with Typescript, which pattern you use?
A. plain simple function
const travel = (destination, transportation) => {
// do something
}
B. curry form
const travel = (destination) => (transportation) => {
// do something
}
C. method chaining
const travel = (destination) => {
return {
transport: (transportation)=>{
// do something
}
}
}
currying and method chaining are similar, because it involves multiple callable, while plain function is only one callable.
I prefer single callable, for a very simple reason, less prone to error when you call it.
Here is how you call them, keep in mind we are using Typescript
A. plain function
travel('North Pole', 'swimming') // ok
travel('North Pole') // ts error
B. Currying
travel('North Pole')('swimming') // ok
travel('North Pole')() // ts error
travel('North Pole') // ok, but do nothing, no ts error
C. Method chaining
travel('North Pole').transport('swimming') // ok
travel('North Pole').transport() // ts error
travel('North Pole') // ok, but do nothing, no ts error
As you can see, it is impossible to call the plain function incorrectly with Typescript.
However this is not the same with currying and method chaining where it is possible to call them partially if you don't pay attention
Still currying and method chaining are good for reusing arguments
const goToNorthPoleWith= travel('North Pole')
goToNorthPoleWith('Airplane')
goToNorthPoleWith('Ship')
so to have the best of both worlds, we should always start from single callable, and if we want to reuse the argument, we can curry it afterwards.
Posted on April 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 17, 2023