【问题标题】:Appropriate way to implement the base abstract state with Akita用秋田实现基本抽象状态的适当方法
【发布时间】:2020-07-24 14:30:57
【问题描述】:

我试图实现这样的事情,但我有点困惑。假设我需要实现各种基于网格的页面,它们的设计方式或多或少相同,但它们每个都有一些特殊性。这就是为什么我需要一些基本的抽象存储/查询服务,我计划在这些服务中实现通用逻辑。

每个网格都将使用BaseLineItem 的子级进行操作:

export interface BaseListItem {
  Id: number;
  StatusId: number;
  // Other properties
}

我尝试实现它的方式

export interface PageState<TListItem extends BaseListItem> extends EntityState<TListItem> {
  // some state properties
}

export abstract class PageStore<TListItem extends BaseListItem, TState extends PageState<TListItem>> extends EntityStore<TState> {
  constructor(initialState: Partial<TState>) {
    super(initialState);
  }

  addNewItems(items: TListItem[]): void {
    this.upsertMany(items);
  }
}

假设我将为每个表单实现订单项、状态和商店的子项,因此我可以添加一些特定于每个表单的特性。但是在那个地方我遇到了addNewItems方法的问题-upsertMany,它显示了以下错误:

Argument of type 'TListItem[]' is not assignable to parameter of type 'getEntityType<TState>[]'.\n  Type 'TListItem' is not assignable to type 'getEntityType<TState>'.\n    Type 'BaseListItem' is not assignable to type 'getEntityType<TState>'.

秋田似乎无法推断实体的类型。

这就是问题所在。如何解决这个问题,而不是到处使用as any(如果我在最基础的级别开始这样做,我将在源代码中失去智能感知)?我是从.Net背景来到前端世界的。也许我不明白什么,这种架构模式在这里不是最好的?我需要一些建议。

【问题讨论】:

    标签: angular typescript angular-akita akita


    【解决方案1】:

    EntityStore.upsertMany 方法将 EntityType[] 的参数数组作为参数数组,该数组是通过使用 typescript helper 类型推断出来的

    export class EntityStore<S extends EntityState = any, EntityType = getEntityType<S>,
                                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    这是这个助手的the source code

    export type getEntityType<S> = S extends EntityState<infer I> ? I : never;
                   
    

    您在实现中使用的Constrained generics 会稍微混淆该助手助手,它无法推断正确的类型并返回与您的泛型类型不匹配的unknown

    也许 TypeScript 将来会更好地推断此类情况下的类型,但现在一个简单的解决方案是在您的代码中使用相同的 Akita 助手而不是 TListItem[]

    addNewItems(items: getEntityType<TState>[]): void {
      this.upsertMany(items);
    }
    

    您可以在 Playground

    中进行测试

    以下是派生类的示例,您可以在其中观察到正确的类型推断。

    另外,您可以查看Akita issue tracker中的类似问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多