redux 如何使React上下文提供程序类型安全

ki1q1bka  于 2022-11-24  发布在  React
关注(0)|答案(1)|浏览(154)

我有一个React上下文提供程序。我用JS写的,但是现在我用TS重写它。我花了很长时间才让类型正常工作。上下文初始化为undefined。后来它被设置为action属性。可以是任何ActionCreatorargs属性可以是任何Action。我尝试了几种不同的方法,但这就像打鼹鼠一样。这是我目前拥有的:

import { createContext, FC, PropsWithChildren, useState } from 'react'
import { Action, ActionCreator } from 'redux'
import { Dispatch, SetStateAction } from "react";

type ModalStateT = {
  action: ActionCreator<any> | undefined
  args: Action | undefined
}

type ModalContextT = {
  modalState: ModalStateT
  setModalState: Dispatch<SetStateAction<ModalStateT>>
  resetModalState: ({action, args}: ModalStateT) => void
}

export const ModalContext = createContext<ModalContextT | undefined>(undefined)

const ModalProvider: FC<PropsWithChildren> = ({ children }) => {

  const defaultState = {
    action: undefined,
    args: undefined,
  }
  const [modalState, setModalState] = useState(defaultState)

  const resetModalState = () => {
    setModalState(defaultState)
  }
  return (
    <ModalContext.Provider value={{ modalState, setModalState, resetModalState }}>
      { children }
    </ModalContext.Provider>
  )
}

export default ModalProvider

我的IDE在此处显示错误value={{ modalState, setModalState, resetModalState }}
这是我得到的错误:

TS2322: Type 'Dispatch<SetStateAction<{ action: undefined; args: undefined; }>>' is not assignable to type 'Dispatch<SetStateAction<ModalStateT>>'.
Type 'SetStateAction<ModalStateT>' is not assignable to type 'SetStateAction<{ action: undefined; args: undefined; }>'.
Type 'ModalStateT' is not assignable to type 'SetStateAction<{ action: undefined; args: undefined; }>'.
Type 'ModalStateT' is not assignable to type '{ action: undefined; args: undefined; }'. Types of property 'action' are incompatible.           
Type 'ActionCreator<any> | undefined' is not assignable to type 'undefined'.        
Type 'ActionCreator<any>' is not assignable to type 'undefined'.

我该如何解决这个问题?提前感谢!

neekobn8

neekobn81#

使用ModalStateT类型注解defaultState

const defaultState: ModalStateT = {
  action: undefined,
  args: undefined,
}

否则TypeScript将推断出限制性更强的类型。
这就是为什么它会给你这样的错误:

Type 'ActionCreator<any>' is not assignable to type 'undefined'.

这是TypeScript告诉您,它将类型推断为undefined,而不是您希望的限制性较低的ActionCreator<any> | undefined

相关问题