I'm trying to assign string type to "player" with TypeScript in React but it's not working simply with player: string as in Option 1.
Option 1:
Object.values(data.val()).forEach((player: string) => {
newPlayers.push(player);
});
The above way produces a ts err:
Argument of type '(player: string) => null' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) => null'. Types of parameters 'player' and 'value' are incompatible. Type 'unknown' is not assignable to type 'string'.ts(2345)
but using the as-syntax, like the following, corrects it. Why is that?
Option 2:
DB_players.once('value', (data) => {
// Fetch players who signed up
const newPlayers: string[] = [];
if (data.val() ) {
Object.values(data.val()).forEach((player) => {
newPlayers.push(player as string);
});
setPlayers(newPlayers); // save the new player list
}
});
playertype is inherited, if only you have typeddata.val().newPlayers. And then usenewPlayersto update the state.forEachIs there already any data innewPlayersbefore this loop? If not, thennewPlayersshould be the array that create from thismap. But the main issue is that the type ofdata.val()isunknown[], so fix that.