簡體   English   中英

Typescript 錯誤:: 類型“數字”不可分配給類型“從不”

[英]Typescript error :: Type 'number' is not assignable to type 'never'

我有一個問題

'類型'數字'不可分配給類型'從不'。'
'類型'數字'不可分配給類型'從不'。'
'類型'字符串'不能分配給類型'從不'。'
'類型'數字'不可分配給類型'從不'。'

在每個idcolcolorheight上。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM