Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Last active March 13, 2023 15:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coolaj86/cfc802175d21c90d74fdc04fa27e23b0 to your computer and use it in GitHub Desktop.
Save coolaj86/cfc802175d21c90d74fdc04fa27e23b0 to your computer and use it in GitHub Desktop.

JSDoc tsc Function Workaround

There's no documentation for this, but it just so happens that if you use the @callback alias some extra machinery kicks in and you can type functions as you would have expected.

/**
- * @typedef {Function} PersonGreet
+ * @callback PersonGreet
 * @param {String} name - other's name
 * @returns {String} - the greeting
 */

/** @type PersonGreet */
let greet = function (name) {
    return `Hello ${name}, my name is Rob the Robot!`;
}

The problem is that @callback is usually incorrect and confusing:

  • all functions are functions
  • not all functions are callbacks
  • in fact, most functions are not callbacks

It's also possible to use TypeScript's proprietary arrow notation, but this generates other errors:

/**
- * @typedef {Function} PersonGreet
- * @param {String} name - other's name
- * @returns {String} - the greeting
+ * @typedef {(
+ *     other: Person
+ * ) => string} PersonGreet
 */

/** @type PersonGreet */
let greet = function (name) {
    return `Hello ${name}, my name is Rob the Robot!`;
}
JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags.
@coolaj86
Copy link
Author

coolaj86 commented Aug 16, 2022

A callback is a pattern where a function is given a reference to another function, which is then invoked. For example [1, -2, 3].map(Math.abs) is a legal way to process an array -- what is the distinction you're trying to draw here? - @RyanCavanaugh (comment)

A "callback" refers to the handler of a result of an asynchronous operation.

As in "I auditioned for a part in the play, and I got a callback" or "I ordered a vanilla frap and I was called back to the counter pick it up".

Since JavaScript is the OG async language, the term callback was adapted from other industries to mean "a function that is given to the event queue to be called back when a result is ready to be handled".

.map() takes a function which, for convenience, may be an anonymous function, but that is not a callback - it is not possible for it to be asynchronous.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment