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

Nei*_*rdi 2 typescript reactjs redux react-redux react-context

我有一个 React 上下文提供程序。我用JS写的,现在用TS重写。我很难让这些类型正常工作。上下文被初始化为未定义。稍后它会设置一个action属性,该属性可以是 any ActionCreator,也可以是一个args属性,该属性可以是 any Action。我尝试了几种不同的方法,但就像打地鼠一样。这就是我目前所拥有的:

\n
import { createContext, FC, PropsWithChildren, useState } from 'react'\nimport { Action, ActionCreator } from 'redux'\nimport { Dispatch, SetStateAction } from "react";\n\ntype ModalStateT = {\n  action: ActionCreator<any> | undefined\n  args: Action | undefined\n}\n\ntype ModalContextT = {\n  modalState: ModalStateT\n  setModalState: Dispatch<SetStateAction<ModalStateT>>\n  resetModalState: ({action, args}: ModalStateT) => void\n}\n\nexport const ModalContext = createContext<ModalContextT | undefined>(undefined)\n\nconst ModalProvider: FC<PropsWithChildren> = ({ children }) => {\n\n  const defaultState = {\n    action: undefined,\n    args: undefined,\n  }\n  const [modalState, setModalState] = useState(defaultState)\n\n  const resetModalState = () => {\n    setModalState(defaultState)\n  }\n  return (\n    <ModalContext.Provider value={{ modalState, setModalState, resetModalState }}>\n      { children }\n    </ModalContext.Provider>\n  )\n}\n\nexport default ModalProvider\n\n
Run Code Online (Sandbox Code Playgroud)\n

我的 IDE 确实在此处显示错误value={{ modalState, setModalState, resetModalState }}

\n

这是我得到的错误:

\n
TS2322: Type 'Dispatch<SetStateAction<{ action: undefined; args: undefined; }>>' is not assignable to type 'Dispatch<SetStateAction<ModalStateT>>'.\nType 'SetStateAction<ModalStateT>' is not assignable to type 'SetStateAction<{ action: undefined; args: undefined; }>'.\nType 'ModalStateT' is not assignable to type 'SetStateAction<{ action: undefined; args: undefined; }>'.\nType 'ModalStateT' is not assignable to type '{ action: undefined; args: undefined; }'. Types of property 'action' are incompatible. \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\nType 'ActionCreator<any> | undefined' is not assignable to type 'undefined'. \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\nType 'ActionCreator<any>' is not assignable to type 'undefined'.\n
Run Code Online (Sandbox Code Playgroud)\n

我怎样才能解决这个问题?提前致谢!

\n

Sly*_*nal 5

defaultState用类型注释你的ModalStateT

const defaultState: ModalStateT = {
  action: undefined,
  args: undefined,
}
Run Code Online (Sandbox Code Playgroud)

否则 TypeScript 将推断出更具限制性的类型。

这就是为什么它会给你这样的错误:

Type 'ActionCreator<any>' is not assignable to type 'undefined'.
Run Code Online (Sandbox Code Playgroud)

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