Home > database >  Typescript, useContext(), error: Argument of type 'never[]' is not assignable to parameter
Typescript, useContext(), error: Argument of type 'never[]' is not assignable to parameter

Time:08-28

I'm trying to use useContext() hook in typescript, but I expireance numerouse errores. useState initialy is equal to empty array of interface Phone which is imported, and then state and setState are passed in value prop .

import { createContext, useState } from 'react';
import { Phone } from '../types/Phone';

type SetValue = (value: Phone[]) => void;

interface LikedContextInterface {
  likedGadgets: Phone[];
  setLikedGadgets: SetValue;
}

export const likedContext = createContext<LikedContextInterface>([]);

type Props = {
  children: React.ReactNode;
};

export const LikedContextProvider: React.FC<Props> = ({ children }) => {
  const [likedGadgets, setLikedGadgets] = useState<Phone[]>([]);

  return (
    <likedContext.Provider value={{ likedGadgets, setLikedGadgets }}>
      { children }
    </likedContext.Provider>
  );
};

in terminal I recieve following errors: Argument of type 'never[]' is not assignable to parameter of type 'LikedContextInterface'. Type 'never[]' is missing the following properties from type 'LikedContextInterface': likedGadgets, setLikedGadgets

Edited!!!

So here is working code:

import { createContext, useState } from 'react';
import { Phone } from '../types/Phone';

type SetValue = (value: Phone[]) => void;

type LikedContextInterface = {
  likedGadgets: Phone[];
  setLikedGadgets: SetValue;
};

export const likedContext = createContext<LikedContextInterface>({
  likedGadgets: [],
  setLikedGadgets: () => {},
});

type Props = {
  children: React.ReactNode;
};

export const LikedContextProvider: React.FC<Props> = ({ children }) => {
  const [likedGadgets, setLikedGadgets] = useState<Phone[]>([]);

  return (
    <likedContext.Provider value={{ likedGadgets, setLikedGadgets }}>
      { children }
    </likedContext.Provider>
  );
};

CodePudding user response:

You have to initialize context correctly by providing initial value which is LikedContextInterface:

export const likedContext = createContext<LikedContextInterface>({
   likedGadgets: [],
   setLikedGadgets: (value: Phone[]) => {},
});
  • Related