Write function overloads using JSDoc and TypeScript

Click for: original source

I like TypeScript, but I prefer the JSDoc syntax for writing it. That should be obvious if you’ve read any of my JavaScript articles, especially Get Started With TypeScript the Easy Way. By Austin Gil.

/**
 * @template numOrStr
 * @param {numOrStr} input
 * @returns {numOrStr extends number ? number : string}
 */
function double(input) {
  if (typeof input === 'number') {
    return input * 2
  }
  return input + input
}

Function overloads are when you define the same function more than once in order to capture different functionality.

The article makes a good job explaining:

  • What is function overloading?
  • Defining function overloads in JSDoc

We liked: TypeScript also offers generics which you can combine with conditional types to determine the input type and conditionally return a specific type based on what the input is. All of that can even work with JSDoc thanks to the @template keyword (which is not well documented). TypeScript is great, and JSDoc is great, but once in a while, the documentation for complex things is sparse. Good read!

[Read More]

Tags javascript app-development web-development nodejs