![](/img/trans.png)
[英]Typescript error:Type 'number' is not assignable to type 'never'
[英]Typescript error :: Type 'number' is not assignable to type 'never'
我有一个问题
'类型'数字'不可分配给类型'从不'。'
'类型'数字'不可分配给类型'从不'。'
'类型'字符串'不能分配给类型'从不'。'
'类型'数字'不可分配给类型'从不'。'
在每个id
、 col
、 color
、 height
上。 4 次,位于ColsContextProvider
中。
而且我认为这可能是Colstate[]
的问题,但我找不到解决方法。
import React, { createContext, Dispatch, useReducer, useContext } from "react";
export const ADD_SQUARE = "ADD_SQUARE" as const;
export const CHANGE_SQUARE = "CHANGE_SQUARE" as const;
export const DELETE_SQUARE = "DELETE_SQUARE" as const;
export type Square = {
id: number;
col: number;
color: string;
height: number;
};
type ColState = Square[];
const ColsStateContext = createContext<ColState[] | void>(undefined);
type Action =
| {
type: "ADD_SQUARE";
id: number;
col: number;
color: string;
height: number;
}
| { type: "CHANGE_SQUARE"; id: number; col: number; color: string }
| { type: "DELETE_SQUARE"; id: number; col: number };
type ColsDispatch = Dispatch<Action>;
const ColsDispatchContext = createContext<ColsDispatch | undefined>(undefined);
function colsReducer(state: ColState[], action: Action) {
switch (action.type) {
case ADD_SQUARE:
return console.log("DELETE_SQUARE");
case CHANGE_SQUARE:
return console.log("CHANGE_SQUARE");
case DELETE_SQUARE:
return console.log("DELETE_SQUARE");
default:
return state;
}
}
export function ColsContextProvider({
children
}: {
children: React.ReactNode;
}) {
const [cols, dispatch] = useReducer(colsReducer, [
[
{
id: 1,
col: 1,
color: "#111",
height: 80
},
{
id: 2,
col: 1,
color: "#aca",
height: 110
}
],
[
{
id: 1,
col: 2,
color: "#cbb",
height: 35
}
],
[
{
id: 1,
col: 3,
color: "#aac",
height: 20
}
]
]);
return (
<ColsDispatchContext.Provider value={dispatch}>
<ColsStateContext.Provider value={cols}>
{children}
</ColsStateContext.Provider>
</ColsDispatchContext.Provider>
);
}
export function useColsState() {
const state = useContext(ColsStateContext);
if (!state) throw new Error("Cols provider problem");
return state;
}
export function useColsDispatch() {
const dispatch = useContext(ColsDispatchContext);
if (!dispatch) throw new Error("Cols provider problem");
return dispatch;
}
您需要在 colsReducer 中返回正确的colsReducer
。
您将在colsReducer
function 中返回console.log()
。 这使得colsReducer
的返回类型为void | Square[][]
void | Square[][]
,无法推断,所以useReducer
中第二个参数的类型变成了never
。
编辑如下代码,看看你必须做什么。
function colsReducer(state: ColState[], action: Action) {
// ...
}
改成:
function colsReducer(state: ColState[], action: Action): ColState[] {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.