[英]Argument of type 'State' is not assignable to parameter of type 'never'
I have just started using typescript with React.我刚刚开始使用 typescript 和 React。 I tried using it with React useReducer hook but I am stuck because of a weird error.
我尝试将它与 React useReducer hook 一起使用,但由于一个奇怪的错误而被卡住了。
Here is my code:这是我的代码:
export interface ContractObj {
company: string;
negotiationRenewalDate: string;
periodEnd: string;
periodStart: string;
scheduleForRenewal: boolean;
contractId: string;
}
type State = {
loading: boolean;
error: boolean;
contractsData: ContractObj[];
};
type Action =
| { type: 'FETCH_SUCCESS'; payload: ContractObj[] }
| { type: 'FETCH_ERROR'; payload: null };
const initialState: State = {
loading: true,
error: false,
contractsData: []
};
const reducer = (state: State, action: Action) => {
switch (action.type) {
case 'FETCH_SUCCESS':
return {
loading: false,
error: false,
contractsData: action.payload
};
case 'FETCH_ERROR':
return {
loading: false,
error: true
};
default: {
return state;
}
}
};
export const Contracts: React.FC<Props> = () => {
const [state, dispatch] = useReducer(reducer, initialState);
It gives me an error when I hover over initialState
ie Argument of type 'State' is not assignable to parameter of type 'never'当我在初始状态上使用
initialState
时,它给了我一个错误,即“状态”类型的参数不可分配给“从不”类型的参数
Make sure to always return the same State
type in the reducer
function.确保在
reducer
function 中始终返回相同的State
类型。 If you hover over reducer
, you see that it currently has following signature:如果您在
reducer
上使用 hover ,您会看到它当前具有以下签名:
const reducer: (state: State, action: Action) => State | {loading: boolean; error: boolean;}
That is, because in case 'FETCH_ERROR'
, contractsData
is left out, which is defined as required property in State
.也就是说,因为在
case 'FETCH_ERROR'
, contractsData
被遗漏了,这在State
中被定义为必需的属性。 It can be fixed easily by adding an explicit return type to reducer
function:它可以通过向
reducer
function 添加显式返回类型来轻松修复:
const reducer = (state: State, action: Action): State => { ... }
and you get the (in this case satisfying.) compile error complaining about the missing property.你得到(在这种情况下令人满意。)编译错误抱怨缺少的属性。 Finally you can either add an empty
contractsData
array in the 'FETCH_ERROR'
case or define the property as optional in the State
type.最后,您可以在
'FETCH_ERROR'
案例中添加一个空的contractsData
数组,或者在State
类型中将该属性定义为可选。
Solution 1:解决方案1:
switch (action.type) {
case 'FETCH_ERROR':
return {
loading: false,
error: true,
contractsData: []
}
}
Solution 2:解决方案2:
type State = {
loading: boolean;
error: boolean;
contractsData?: ContractObj[];
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.