Home > Blockchain >  Type"X' is not assignable to type "Y" with typescript
Type"X' is not assignable to type "Y" with typescript

Time:10-20

I'm new in TS, and I tried to use it with the context API, but I encountered this problem: when I try to pass the value in the provider I end up with this problem :

"Type '{ players: Player[]; }' is not assignable to type 'Player[]'.
Object literal may only specify known properties, and 'players' does not exist in type 'Player[]'.ts(2322)"

Here is my code :

interface Player {
  players: [];
}

type WithChildren<T = {}> = T & { children: JSX.Element };

const PlayersProvider = ({ children }: WithChildren) => {
  const [players, setPlayers] = useState<Player[]>([]);
  useEffect(() => {
    axios.get<{ players: Player[] }>(baseUrl   "/players").then((response) => {
      setPlayers(response.data.players);
    });
  }, []);

  return (
    <PlayerContext.Provider value={{ players }}>
      {children};
    </PlayerContext.Provider>
  );
};

It worked fine when I had it in component but since I externalize in a context provider it broke. Can someone explain me what's wrong?

CodePudding user response:

It seems that you are passing { players } (of type { players: Player[]; }) instead of players (of type Player[]) as a value to the context provider.

You should replace:

<PlayerContext.Provider value={{ players }}>

by:

<PlayerContext.Provider value={players}>
  • Related