Domenik Reitzner
Domenik Reitzner

Reputation: 1613

JSDOC - typedef for function with sub function

I currently have the following issue with the type-definition for sub-functions.

Example code:

/** @type {$timeout} */
const $timeout;
// this works with intellisense
const promise = $timeout(() => callback(1234), 999);
// this does not
const wasCanceled = $timeout.cancel(promise);

Example jsdoc type-definiton:

/**
 * @typedef {_timeout} $timeout
 */
/**
 * @callback _timeout
 *
 * @param {function()=} fn A function, whose execution should be delayed.
 * @param {number=} [delay=0] Delay in milliseconds.
 * @param {boolean=} [invokeApply=true] 
 * @param {...*=} Pass additional parameters to the executed function.
 * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
 *   will be resolved with the return value of the `fn` function.
 */
/**
 * @callback _timeout#cancel
 *
 * @description
 * Cancels a task associated with the `promise`. As a result of this, the promise will be
 * resolved with a rejection.
 *
 * @param {Promise=} promise Promise returned by the `$timeout` function.
 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
 *   canceled.
 */

I would love to type this correctly, but I didn't quite figure out the way to do it and the docs didn't reveal anything helpful.

Also didn't find anything on here ;)

Upvotes: 0

Views: 675

Answers (1)

Balah
Balah

Reputation: 2540

You have almost all the right pieces; the missing key is using an intersection type. Tweak your "sub function" as follows:

/**
 * @callback _cancelTask
 *
 * @description....

Then on your $timeout typedef, do the following:

/**
* @typedef {{cancel: _cancelTask} & _timeout} $timeout
*/

That will create cancel() as a property of $timeout

Upvotes: 1

Related Questions