【问题标题】:Getting a Typescript error saying, some type is not assignable to parameter of type 'ReducerWithoutAction<any>'?收到 Typescript 错误说,某些类型不能分配给“ReducerWithoutAction<any>”类型的参数?
【发布时间】:2021-06-30 00:41:04
【问题描述】:

我正在构建一个练习表格,并使用useReducer() 来管理状态。我得到的 Typescript 错误与它有关,我已经尝试解决它但没有运气。

完整代码可在此处获得(路径:src/components/Input.tsx): CodeSandbox

完全错误:

/form/src/components/Input.tsx(47,47) 中的 TypeScript 错误: 没有重载匹配此调用。 Overload 1 of 5, '(reducer: ReducerWithoutAction, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]',给出以下错误。 '(state: InputState, action: InputAction) => { value: string | 类型的参数不明确的; isValid: 布尔值 |不明确的;触摸:布尔值; }' 不可分配给“ReducerWithoutAction”类型的参数。 TS2769

45 | const Input: React.FC<Props> = (props) => {
46 |     console.log(props.required);
47 |     const [inputState, dispatch] = useReducer(inputReducer, {
   |                                              
48 |         value: props.initialValue,
49 |         isValid: false,
50 |         touched: false

【问题讨论】:

  • 您必须将显式类型参数传递给useReducer,编译器无法推断出正确的类型。 google.com/…
  • 是的,我已经构建了一个接口并将其附加到 inputReducer 函数: const inputReducer = (state: InputState, action: InputAction) =>... 根据我读过的内容,我没有需要在下面添加任何东西: const [inputState, dispatch] = useReducer(inputReducer...

标签: javascript reactjs typescript


【解决方案1】:

这是因为InputAction 有属性valueisValid 作为可选(他们有?)。这使得InputAction 相当于:

interface InputAction {
    value: string | undefined;
    isValid: boolean | undefined;
    touched: boolean;
}

InputState各自的属性无关:

interface InputState {
    value: string,
    isValid: boolean,
    touched: boolean
}

您可以通过根据需要设置ActionInput 的相应属性(删除?)或将InputState 的属性设置为可选来解决此错误。

【讨论】:

  • 我不明白 InputAction 和 InputState 是无关的,我没有扩展任何东西。我看不出有什么问题。我尝试了你的建议,但没有奏效。您可能仍然正确,所以您可以进一步详细说明。谢谢
  • 顺便说一下,InputActionInputState 在传递给 useReducer 时实际上是相关的。请参阅此处的定义 => sumologic.com/blog/react-hook-typescript at "useReducer TypeScript Example"
猜你喜欢
  • 2017-02-07
  • 2019-06-21
  • 2021-06-09
  • 1970-01-01
  • 2021-12-03
  • 2019-09-07
  • 2017-06-21
  • 2017-01-30
  • 2021-06-22
相关资源
最近更新 更多