【问题标题】:Redux createStore<StoreState> produces an error: Expected 4 type arguments, but got 1Redux createStore<StoreState> 产生错误:Expected 4 type arguments, but got 1
【发布时间】:2019-09-30 21:56:35
【问题描述】:

我正在关注TypeScript-React-Starter tutorial,并在src/index.tsx 中创建商店。从教程中,

const store = createStore<StoreState>(enthusiasm, {
  enthusiasmLevel: 1,
  languageName: 'I\'m fluent in Math and Klingon'
});

产生错误

Expected 4 type arguments, but got 1.


Issue #136 建议使用

import { EnthusiasmAction } from './actions/index';

const store = createStore<StoreState, EnthusiasmAction, any, any>(enthusiasm, {
  enthusiasmLevel: 1,
  languageName: 'I\'m fluent in Math and Klingon'
});

在其他类似的解决方案中,但这会产生另一个错误:

Argument of type '(state: StoreState, action: EnthusiasmAction) => StoreState' is not assignable to parameter of type 'Reducer<StoreState, EnthusiasmAction>'.
Types of parameters 'state' and 'state' are incompatible.
  Type 'StoreState | undefined' is not assignable to type 'StoreState'.
    Type 'undefined' is not assignable to type 'StoreState'.

问题已关闭,但其他人也遇到了同样的问题。


如何创建我的商店?

【问题讨论】:

    标签: reactjs typescript npm redux react-redux


    【解决方案1】:
    const store = createStore<StoreState>(enthusiasm, {
      enthusiasmLevel: 1,
      languageName: 'I\'m fluent in Math and Klingon'
    });
    

    产生错误

    Expected 4 type arguments, but got 1.
    


    这是由于我使用 Redux 4.0.1 时使用 Redux 3.7.2 的教程。


    解决方案 #1

    我安装了 Redux 3.7.2:

    npm install redux@3.7.2
    

    由于我使用的是TypeScript-React-Starter tutorial,因此这是最适合本教程的解决方案。


    解决方案 #2

    我将 createStore() 函数更改为采用 4 个类型参数作为错误消息的建议:

    const store = createStore<StoreState, Action<any>, unknown, unknown>(enthusiasm, {
      enthusiasmLevel: 1,
      languageName: 'I\'m fluent in Math and Klingon',
    });
    

    现在我可以使用 Redux 4.0.1 继续 tutorial。 :-)

    【讨论】:

      【解决方案2】:

      在创建 store 时尝试在 reducer 中创建初始状态。它应该可以工作。

      export interface IStoreState {
          languageName: string;
          enthusiasmLevel: number
      }
      
      const initState: IStoreState = {
          languageName: "TypeScript",
          enthusiasmLevel: 0
      }
      

      【讨论】:

        猜你喜欢
        • 2020-09-20
        • 1970-01-01
        • 1970-01-01
        • 2019-03-02
        • 1970-01-01
        • 2022-12-30
        • 2021-07-28
        • 2021-03-01
        • 2020-09-05
        相关资源
        最近更新 更多