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

NGRX Signal Store使用signalStoreFeature结合withState时类型不匹配

NgRx Signal Store 复用特性类型错误问题

我定义了一个可复用的store特性withPaginatedData,它要求集成该特性的store必须实现固定签名的loadData方法。原本这个特性运行正常,但当通过withState()为store添加状态属性后,出现大量类型错误,提示loadData方法在MethodsDictionary中缺失,看起来添加其他状态后该方法不再被类型系统识别。

代码示例

import { signalStore, signalStoreFeature, type, withMethods, withState } from '@ngrx/signals';
import { Observable, of } from 'rxjs';

interface LoadDataOptions {
  page: number;
  size: number;
}

interface MyEntity {
  id: string;
}

export function withPaginatedData<Entity, Filters extends object | undefined = undefined>() {
  return signalStoreFeature(
    {
      methods: {
        loadData: type<(options: LoadDataOptions, filters?: Filters) => Observable<Entity>>(),
      },
    },
    withMethods((store) => ({
      foo: () => {
        store.loadData({ page: 1, size: 100 });
      },
    })),
    // 其他逻辑
  );
}

export const MyStore = signalStore(
  { providedIn: 'root' },
  withState({ selectedId: '' }),
  withMethods((state) => ({
    loadData: (options: LoadDataOptions) => {
      console.log(options, state.selectedId());

      const demoData: MyEntity = { id: '1' };
      return of(demoData);
    },
  })),
  withPaginatedData<MyEntity, undefined>(),
);

注释掉withState({ selectedId: '' }),及相关console.log代码后,类型校验恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 13:30:58