我有一個 React 背景關系提供程式。我用 JS 寫的,但我現在用 TS 重寫它。我花了很長時間讓型別正常作業。背景關系使用未定義初始化。稍后,它設定了一個action
可以是 any的屬性ActionCreator
和一個可以是 any 的屬性。我嘗試了幾種不同的方法,但這就像打痣一樣。這是我目前擁有的: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'.
我怎樣才能解決這個問題?提前致謝!
uj5u.com熱心網友回復:
defaultState
用型別注釋你ModalStateT
:
const defaultState: ModalStateT = {
action: undefined,
args: undefined,
}
否則 TypeScript 將推斷出更嚴格的型別。
這就是為什么它給你這樣的錯誤:
Type 'ActionCreator<any>' is not assignable to type 'undefined'.
那是 TypeScript 告訴你它是推斷型別而不是你想要undefined
的限制較少的型別。ActionCreator<any> | undefined
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527581.html
上一篇:從父類傳遞時道具未定義
下一篇:cdk無法連接到unix:///var/run/docker.sock上的Docker守護程式。docker守護行程是否正在運行?-部署cdk時出錯