#javascript #reactjs #typescript #next.js
#javascript #reactjs #typescript #next.js
Вопрос:
Это мой AppContext.tsx
import React, { useState, createContext } from "react";
import { Iitem } from "../utils/interfaces";
interface AppContext {
showModal: boolean;
setShowModal: React.Dispatch<React.SetStateAction<boolean>>;
cart: Array<Iitem>;
setCart: React.Dispatch<React.SetStateAction<never[]>>;
currentSelection: object | null;
setCurrentSelection: React.Dispatch<React.SetStateAction<null>>;
}
export const AppContext = createContext<AppContext>({
showModal: false,
setShowModal: () => {},
cart: [],
setCart: () => {},
currentSelection: null,
setCurrentSelection: () => {},
});
export const AppState: React.FC = ({ children }) => {
const [showModal, setShowModal] = useState(false);
const [cart, setCart] = useState([]);
const [currentSelection, setCurrentSelection] = useState(null);
return (
<AppContext.Provider
value={{
showModal,
setShowModal,
cart,
setCart,
currentSelection,
setCurrentSelection,
}}
>
{children}
</AppContext.Provider>
);
};
MyComponent.tsx
const MyComponent = () => {
const {setCart} = useContext(AppContext);
const myFunc = () => {
setCart((prevState) => [...prevState, newItem]);
}
}
Когда я пытаюсь вызвать setCart
метод, TypeScript выдает ошибку, и если я наведу на (prevState)
него курсор, отображается:
(parameter) prevState: never[]
Argument of type '(prevState: never[]) => any[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
Type '(prevState: never[]) => any[]' is not assignable to type '(prevState: never[]) => never[]'.
Type 'any[]' is not assignable to type 'never[]'.
Type 'any' is not assignable to type 'never'.ts(2345)
Как я могу это исправить?
Ответ №1:
В интерфейсе AppContext для типа установлено значение never, поэтому измените тип, который вы ожидаете увидеть.
interface AppContext {
showModal: boolean;
setShowModal: React.Dispatch<React.SetStateAction<boolean>>;
cart: Array<Iitem>;
setCart: React.Dispatch<React.SetStateAction<any[]>>;
currentSelection: object | null;
setCurrentSelection: React.Dispatch<React.SetStateAction<null>>;
}
Ответ №2:
Похоже, это решает проблему
cart: Array<Iitem>;
и….
setCart: React.Dispatch<React.SetStateAction<Array<Iitem>>>;
и….
const [cart, setCart] = useState<Array<Iitem>>([]);