reactjs - 我如何使我的 React 上下文提供程序类型安全
我有一个 React 上下文提供者。我最初是用 JS 写的,但现在我正在用 TS 重写它。我在让类型正常工作方面遇到了很多麻烦。上下文最初初始化为 undefined。后来它被设置为一个带有 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'.
我该如何修复这个?提前谢谢!
答案#1
使用 ModalStateT 类型注解你的 defaultState:
const defaultState: ModalStateT = {
action: undefined,
args: undefined,
}
否则 TypeScript 会推断出更严格的类型。
这就是为什么它会给你类似这样的错误:
Type 'ActionCreator<any>' is not assignable to type 'undefined'.
这是 TypeScript 告诉你,它将类型推断为 undefined,而不是你希望的较少限制的 ActionCreator<any> | undefined。
