【问题标题】:can't assign reducer on typescript?不能在打字稿上分配减速器?
【发布时间】:2019-03-15 11:19:57
【问题描述】:

我在这里关注关于 redux + typescript 的微软教程:https://github.com/Microsoft/TypeScript-React-Starter 但不知何故在最后一部分我被卡住了:

const store = createStore<StoreState, any, any, any>(
  enthusiasm,
  {
    enthusiasmLevel: 1,
    languageName: 'TypeScript'
  },
  composeEnhancers(applyMiddleware(thunk))
);

这是我在下面的屏幕截图中遇到的错误:

Argument of type '(state: StoreState, action: EnthusiasmAction) => StoreState' is not assignable to parameter of type 'Reducer<StoreState, any>'.
  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'.ts(2345)

我相信我已经关注了一切,在这里,我也想添加 thunk,但是我在争论的热情上遇到了错误,我不知道为什么,帮助?

【问题讨论】:

    标签: javascript reactjs typescript redux


    【解决方案1】:

    关键部分在这里:

    键入'StoreState | undefined' 不可分配给类型 'StoreState'。
          类型 'undefined' 不可分配给类型 'StoreState'.ts(2345)

    听起来您需要启用严格的空检查 (--strictNullChecks)。没有它们,基本上代码中的每种类型都是隐式的YourType | undefined,但是您提供此回调的内容似乎需要一个完全接受/提供StoreState,而不是StoreState | undefined 的回调。更多关于可空类型和严格空检查here

    (或者我可能有错误的一端,你确实启用了严格的空检查,但你使用的期望它们不是。但是我认为我的方法是正确的。)

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      相关资源
      最近更新 更多