Typescript API Design: Single Callable Or Multiple Callable

Acid Coder
2 min readApr 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 do 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.

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 a single callable, and if we want to reuse the argument, we can curry it afterwards.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Acid Coder
Acid Coder

Written by Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)

No responses yet

Write a response