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

标签 reactjs typescript redux react-redux react-context

我有一个 React 上下文提供程序。我用JS写的,现在用TS重写。我很难让这些类型正常工作。上下文被初始化为未定义。稍后使用 action 属性(可以是任何 ActionCreator)和 args 属性(可以是任何 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'.

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

最佳答案

注释您的defaultStateModalStateT类型:

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

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

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

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

这是 TypeScript 告诉你它推断出的类型为 undefined而不是限制较少的 ActionCreator<any> | undefined你想要的样子。

关于reactjs - 如何使我的 React 上下文提供程序类型安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74311348/

相关文章:

reactjs - Nginx 404 静态文件( react 应用程序)

redux - 如何正确输入传奇

reactjs - 创建具有远程排序、分页、过滤功能的表

javascript - 渲染的 HTML 与 React 组件不同步

javascript - Beginner Node/React/MySQL -> 查询数据库并显示结果

javascript - react native : Opening push notification opens app but does not navigate to related content

typescript - 获取识别为接口(interface)的 typescript 类

javascript - 如何将 @types/module 与为其编写类型的 npm 模块结合使用?

javascript - 用类声明一个变量

node.js - 如何持 Passport 开会?