从@ ngrx / entity / Dictionary获取错误的类型

问题描述

我有一些基于NGRX的映射,如下所示,其中一个正在返回:

Type 'normalizedAppState[key]' does not satisfy the constraint 'EntityState<normalizedAppState[key]["entities"][number]>'.
   Type 'InstrumentState' is not assignable to type 'EntityState<normalizedAppState[key]["entities"][number]>'.
     Types of property 'entities' are incompatible.
       Type 'Dictionary<IInstrument>' is not assignable to type 'Dictionary<normalizedAppState[key]["entities"][number]>'.
         Type 'IInstrument' is not assignable to type 'normalizedAppState[key]["entities"] [number]'.

我的映射

//* Minimal NGRX *//

interface DictionaryNum<T> {
    [id: number]: T | undefined;
}
class Dictionary<T> implements DictionaryNum<T> {
    [id: string]: T | undefined;
    // [id: number]: T | undefined; // this solves the problem
}
interface EntityState<T> {
    ids: number[];
    entities: Dictionary<T>;
}

//* *//

const featureNames = {
    instrument: 'instrument',} as const

interface EntityStateActions<
  TState extends EntityState<TState['entities'][number]>
> {}

interface IInstrument {}

interface InstrumentState extends EntityState<IInstrument> {}

abstract class normalizedAppState {
  [featureNames.instrument]: InstrumentState;
}

错误

export type normalizedFeatureActions = {
  [key in keyof typeof featureNames]: EntityStateActions<
    normalizedAppState[key] --> The error happens here
  >;
};

如果我将Dictionary<T>类更改为

错误就会消失
class Dictionary<T> implements DictionaryNum<T> {
    [id: string]: T | undefined;
}

class Dictionary<T> implements DictionaryNum<T> {
    [id: number]: T | undefined;
}

但是我不想更改第三方类别。而且使用我自己的字典也有问题​​,因为有必要替换其他几种类型。

如何摆脱这个错误

Playground Link

解决方法

我找到的解决方案是在我的接口中放入更多参数,这样他们就不需要通过索引访问类型。

interface EntityActions<TEntity,TState extends EntityState<TEntity>>{}

abstract class AppState {
  [featureNames.instrument]: InstrumentState;
}

export type FeatureActions = {
  [featureNames.instrument]: EntityActions<IInstrument,InstrumentState>
};

Solution