Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSDoc overloaded function not working with TypeScript

I am using the JSDoc overload syntax as suggested in other questions and online, not sure if I have it correctly, but here goes:

/**
 * @param {string} param
 * @returns {'string result'}
 *//**
* @param {number} param
* @returns {'number result'}
*/
function overloaded(param) {
  switch (typeof param) {
    case 'string': return 'string result';
    case 'number': return 'number result';
  }

  throw new Error(`Invalid type: ${typeof param}`);
}

overloaded('seven');
overloaded(7);

This function should return string result exactly if the type of the input parameter is string and it should return number result exactly if the type of the input parameter is number. In normal TypeScript this would be:

function overloaded2(param: string): 'string result';
function overloaded2(param: number): 'number result';
function overloaded2(param: string | number): 'string result' | 'number result' {
switch (typeof param) {
    case 'string': return 'string result';
    case 'number': return 'number result';
}

throw new Error(`Invalid type: ${typeof param}`);
}

overloaded2('seven');
overloaded2(7);

The problem is that the JSDoc as I have it is probably incorrect because TypeScript inference as provided by the VS Code language service fails to pick up the overload:

Basically it only sees the first overload. Is the JSDoc support in TypeScript advanced enough for me to be able to type the JavaScript code to the same degree as the TypeScript counterpart? How would that look?

like image 842
Tomáš Hübelbauer Avatar asked Jan 18 '19 22:01

Tomáš Hübelbauer


1 Answers

UPDATE: Included my preferred method

/**
 * @callback ConvertNumberToArray
 * @param {number} input
 * @return {number[]}
 *
 * @callback keepStrings
 * @param {string} input
 * @return {string}
 */

/**
 * @type {ConvertNumberToArray & keepStrings}
 */
const parse = input => {
  if (typeof input === 'number') return [input]
  else return input
}

What it looks like in VSCode

enter image description here


ORIGINAL POST: Have a look here https://austingil.com/typescript-function-overloads-with-jsdoc/

Example

/**
 * @type {{
 * (input: number) => number;
 * (input: string) => string;
 * }}
 */
const double = (input) => {
  if (typeof input === 'number') {
    return input * 2
  }
  return input + input
}
like image 76
JakeDK Avatar answered Sep 27 '22 18:09

JakeDK