You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JSDoc为自定义Store的subscribe方法添加类型注解

解决自定义Svelte Store的subscribe类型标注问题

你遇到的报错是因为Readable是类型别名而非命名空间,没法直接通过Readable.subscribe引用它的属性类型。这里提供两种实用的解决方式:

方法一:通过索引类型提取subscribe的类型

利用typeof Readable<number>['subscribe']直接获取Readable接口中subscribe方法的类型,就能正确给subscribe属性标注:

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

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

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

方法二:用交叉类型合并Readable与自定义方法

既然自定义Store是Readable加上额外方法,直接用交叉类型&合并两种类型更简洁,无需手动声明subscribe的类型:

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

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

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

注意:你之前尝试的@extends无效,是因为JSDoc的@extends仅适用于类继承场景,对象类型的合并需要用交叉类型。

内容的提问来源于stack exchange,提问作者Corrl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:52:39