Redux createStore<StoreState> 产生错误:预期 4 个类型参数,但得到 1 个

Sup*_*ade 5 npm typescript reactjs redux react-redux

我正在遵循TypeScript-React-Starter 教程,并在src/index.tsx. 从教程来看,

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

产生错误

Expected 4 type arguments, but got 1.
Run Code Online (Sandbox Code Playgroud)


问题 #136建议使用

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

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

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

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'.
Run Code Online (Sandbox Code Playgroud)

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


我如何创建我的商店?

Sup*_*ade 2

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

产生错误

Expected 4 type arguments, but got 1.
Run Code Online (Sandbox Code Playgroud)


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


解决方案#1

我安装了 Redux 3.7.2:

npm install redux@3.7.2
Run Code Online (Sandbox Code Playgroud)

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


解决方案#2

我更改了 createStore() 函数以采用 4 个类型参数,如错误消息所示:

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

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