【问题标题】:Get the type of redux's state获取 redux 的 state 类型
【发布时间】:2022-01-09 01:38:12
【问题描述】:

我想获得一个用于 redux 状态的类型,它将用于模拟所述状态。

到目前为止,我发现我有这个 Reducer:

(alias) const reducer: {
    selectedElement: Reducer<StructureElement, AnyAction>;
    fetchedState: Reducer<FetchedState, AnyAction>;
    ... 10 more ...;
    mesApi: Reducer<...>;
}

所以我想做的,是以某种方式从Reducer&lt;/here/, AnyAction&gt;; 部分内部获取StructureElementFetchedState 等等。

我怎样才能做到这一点?

或者有没有更好的方法来获得组合状态类型?它必须自动完成。我不想在应该自动生成的两个地方更改类型。

如果我试试这个:

type State = typeof reducer;

我明白了

Type '{ selectedElement: Reducer; fetchedState: Reducer; ... 10 更多 ...; mesApi: 减速器<...>; }' 不可分配给类型 '{ selectedElement?: { stateId: string;父ID:字符串; hasChild:布尔值;路径列表:字符串[];名称:字符串;颜色:字符串; isActive:布尔值;级别:数字;孩子们?: ...[];键?:字符串;类型:状态类型; }; ... 11 更多 ...; mesApi?: { ...; }; }'。 属性“selectedElement”的类型不兼容。

这是有道理的。

【问题讨论】:

    标签: javascript typescript redux types react-redux


    【解决方案1】:

    好吧,我是愚蠢的。我从基本设置中得到了类似的东西:

    export type RootState = ReturnType<typeof store.getState>;
    

    而且它似乎可以解决问题。

    【讨论】:

      【解决方案2】:

      我个人为我想要在我的状态中的每个功能创建一个切片,然后我有一个文件,我将首先在其中声明和导出我的 RootState 类型,然后我将组合我的所有减速器。

      export interface RootState {
        pokemon: pokemonState;
        pokemonTrainer: pokemonTrainerState;
      }
      
      const reducer = combineReducers<RootState>({
        pokemon: pokemonSLice,
        pokemonTrainer: pokemonTrainerSlice,
      });
      

      其中pokemonStatepokemonTrainerState 是每个功能的类型。
      然后我会在任何需要的地方使用RootState

      【讨论】:

        【解决方案3】:

        我建议简单地对其进行显式建模,然后在需要它们的地方导入这些类型:

        export type UserState = {
            readonly isLoggedIn: boolean;
            // other user state here
        };
        
        // Type for entire global redux state
        export type AppState = {
            users: UserState;
            // other sub-states here
        };
        

        【讨论】:

        • 这是一个很好的做法,因为 Typescript 编译器应该做的一件事是检查 reducer 在所有情况下使用正确的数据类型输出状态。如果状态是推断出来的,那可能不会发生。
        猜你喜欢
        • 1970-01-01
        • 2016-10-17
        • 2021-08-19
        • 2016-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-13
        相关资源
        最近更新 更多