我有一个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条答案
按热度按时间neekobn81#
使用
ModalStateT
类型注解defaultState
:否则TypeScript将推断出限制性更强的类型。
这就是为什么它会给你这样的错误:
这是TypeScript告诉您,它将类型推断为
undefined
,而不是您希望的限制性较低的ActionCreator<any> | undefined
。