[英]Type"X' is not assignable to type "Y" with typescript
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 :我是 TS 新手,我尝试将它与上下文 API 一起使用,但是我遇到了这个问题:当我尝试在提供程序中传递值时,我最终遇到了这个问题:
"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)"对象字面量只能指定已知的属性,而 'players' 不存在于类型 '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?
有人可以解释我有什么问题吗?
It seems that you are passing { players }
(of type { players: Player[]; }
) instead of players
(of type Player[]
) as a value to the context provider.似乎您将
{ players }
{ players: Player[]; }
{ players }
(类型为{ players: Player[]; }
)而不是players
(类型为Player[]
)作为值传递给上下文提供者。
You should replace:你应该更换:
<PlayerContext.Provider value={{ players }}>
by:经过:
<PlayerContext.Provider value={players}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.