【发布时间】:2019-12-15 08:59:13
【问题描述】:
我是 Typescript 的新手,在使用 useContext 和 useReducer 挂钩时,我的变量 state 出现以下错误:
输入'{状态:{};派遣:派遣; }' 不可分配给 类型'{经纬度:空;搜索词:空;预订ID:空;我的销:空; selectedPin:空;选择卡:空; selectedCardPin:空; }'。
对象字面量只能指定已知属性,而“状态”不 存在于类型 '{ latlng: null;搜索词:空;预订ID:空; 我的销:空; selectedPin:空;选择卡:空;已选择的CardPin: 空值; }'.ts(2322)
这是我的app.tsx:
const App = () => {
const initialState = useContext(Context)
const [state, dispatch] = useReducer(reducer, initialState)
return(
<Context.Provider value={{ state // <-this is where the error occurs//, dispatch }}>
...
</Context.Provider>
)
以下是我的context.jsx:
const Context = createContext({
latlng: null,
searchTerm: null,
bookingId: null,
myPin: null,
selectedPin: null,
selectedCard: null,
selectedCardPin: null,
})
修订:
根据建议,我已将 `context.tsx' 更改为以下内容,但仍然收到错误消息:
类型参数 '{ latlng: null;搜索词:空;预订ID:空; 我的销:空; selectedPin:空;选择卡:空;已选择的CardPin: 空值; }' 不可分配给“MyContextType”类型的参数。
对象字面量只能指定已知属性,而 'latlng' 可以 'MyContextType'.ts(2345) 类型中不存在
import { createContext } from 'react'
interface MyContextType {
dispatch: React.Dispatch<any>,
state: {
latlng?: any,
searchTerm?: any,
bookingId?: any,
myPin?: any,
selectedPin?: any,
selectedCard?: any,
selectedCardPin?: any,
}
}
const Context = createContext<MyContextType>({
latlng: null,
searchTerm: null,
bookingId: null,
myPin: null,
selectedPin: null,
selectedCard: null,
selectedCardPin: null,
})
export default Context
第二次修订:
当我更改我的context.jsx 以匹配createContext 的内容时:
interface MyContextType {
latlng?: any,
searchTerm?: any,
bookingId?: any,
myPin?: any,
selectedPin?: any,
selectedCard?: any,
selectedCardPin?: any,
}
const Context = createContext<MyContextType>({
latlng: null,
searchTerm: null,
bookingId: null,
myPin: null,
selectedPin: null,
selectedCard: null,
selectedCardPin: null,
})
context.jsx 中的错误已消失,但会导致 app.jsx 中出现类型错误。
输入'{状态:{};派遣:派遣; }' 不可分配给 输入“MyContextType”。对象字面量只能指定已知 属性,并且类型中不存在“状态” 'MyContextType'.ts(2322)
<Context.Provider value={{ state //<-- here //, dispatch }}>
</Context.Provider>
【问题讨论】:
-
声明一个具有可选属性的类型,例如
interface MyContextType = { dispatch: Function, state: { latlng?: string, ... } },然后使用createContext<MyContextType>({ ... }) -
@p.s.w.g 我按照你说的做了更改,但仍然出现错误
-
对不起,没有更明确。您必须提供
dispatch并包装state以完全匹配您希望在<Context.Provider value={}中使用的内容,例如createContext<MyContextType>({ dispatch: null, state: { latlng: null, ... }}). -
@pswg 似乎如果我将接口与
context.jsx中的状态相匹配,它会解决context.jsx中的类型错误,但它会导致app.jsx中的错误,其中状态来自值不'不认识MyContextType -
也许你需要
interface MyContextType = { dispatch: Dispatch<any>, state: any }?这会牺牲显着的类型安全性,但无论如何,您的状态对象似乎定义得非常松散。
标签: javascript reactjs typescript typescript-typings react-hooks