Search code examples
sveltejsdoc

How to type the subscribe method of a custom store with JSDoc


Given a simple custom store factory function

/**
 * @template T generic data to handle in store
 * @typedef {import('svelte/store').Readable<T>} Readable
 */

/**
 * @typedef {Object} MyCustomStore
 * @property {Readable.subscribe} subscribe
 * @property {() => void} myMethod
 */
/**
 *@returns {MyCustomStore}
 */
function createMyCustomStore() {
    const { subscribe, set, update } = writable(0);
    return {
        subscribe,
        myMethod() {
            console.log('...');
        },
    };
}

how to correctly type the subscribe method?

Readable.subscribe gives

Cannot access Readable.subscribe because Readable is a type, but not a namespace.

Since the Readable also only has the subscribe method I wonder if MyCustomStore type could extend it, but then the property isn't found anymore

/**
* @typedef {Object} MyCustomStore
* @extends Readable<number>
* @property {() => void} myMethod
*/

Solution

  • Properties need to be accessed via indexer, should be this:

    /**
     * @typedef {Object} MyCustomStore
     * @property {Readable<number>['subscribe']} subscribe
     * @property {() => void} myMethod
     */
    

    @extends appears to be only valid for @class.
    You could use an intersection instead:

    /**
    * @typedef {Object} MyCustomStoreExtension
    * @property {() => void} myMethod
    */
    
    /**
     * @typedef {Readable<number> & MyCustomStoreExtension} MyCustomStore
     */