kungfooman / RuntimeTypeInspector.js

Checking JSDoc types at runtime for high-quality types - Trust is good, control is better.
MIT License
8 stars 0 forks source link

Implement JSDoc function overloading runtime type validations #42

Open kungfooman opened 10 months ago

kungfooman commented 10 months ago

There are multiple ways to do it, for example:

/**
 * @type {{
 *   (a: number, b: number): number;
 *   (a: string, b: string): string;
 * }}
 */
const add = function(a, b) {
    return a + b;
}
const addString = add("a", "b");
const addNumber = add(1, 2);
/**
 * @type {{
 *   (input: number): number;
 *   (input: string): string;
 * }}
 */
const double = (input) => {
  if (typeof input === 'number') {
    return input * 2
  }
  return input + input;
}
const doubleString = double("test");
const doubleNumber = double(123);

TS Playground

But it looks very strange and even shows errors in TS Playground... personally I think this would be nice:

/**
 * @typedef {(a: number, b: number) => number} AddNumber
 * @typedef {(a: string, b: string) => string} AddString
 * @type {AddNumber | AddString}
 */
function add(a, b) {
    return a + b;
}

(but that style isn't supported by TS so far)