skip to Main Content

I’m not sure how to properly type an array that contains objects. Sorry if this is worded poorly, let me know if you have any questions. Thank you!

const gamesPlayed = { id: 1, gamePlayedId: 1, completed: "2022-09-20T00:00:00.000Z", players: (2) [{ id: 1, score: 21, userId: 1, gameId: 1, guestName: "John Doe", id: 1, score: 21 },
{ id: 2, score: 20, userId: 2, gameId: 1, guestName: "Bob Doe", id: 2, score: 20}}


 {gamesPlayed?.players !== undefined &&
                gamesPlayed?.players.map(
                  (p1: Array<Object>, p2: Array<Object>) => ( //this line is where I'm struggling
                    <GameIconAndRecord
                      WinLoss={`${p1[0]?.score} / ${p2[1]?.score} `}
                    >
                      <EightBallIcon size="small" />
                    </GameIconAndRecord>
                  )
                )}

right now I’m getting the type error "Property ‘score’ does not exist on type ‘Object’". I hard coded the "gamesPlayed" as a variable in this example, however it’s actually coming from a database.

2

Answers


  1. looking at your code, the problem comes from the way you’re using Array.prototype.map() which only accepts 1 argument and here you’re trying to pass in 2. Try this:

    gamesPlayed?.players?.map(
      (player: Player) => (
        <GameIconAndRecord
          WinLoss={`${player.score}`}
        >
    

    I’m assuming here that you have a Player interface declared. If not, you can take that part out.

    Login or Signup to reply.
  2. I’m not sure, what is your business problem to solve here, but i assume that you have to display component, which shows information about result of game played between two players:

    const game = { 
        id: 1, 
        gamePlayedId: 1, 
        completed: "2022-09-20T00:00:00.000Z", 
        players: [{ 
            id: 1, 
            score: 21, 
            userId: 1, 
            gameId: 1, 
            guestName: "John Doe" 
        }, { 
            id: 2, 
            score: 20, 
            userId: 2, 
            gameId: 1, 
            guestName: "Bob Doe"
        }]
    }
    

    If it’s the case, you don’t need map(...) here:

     { (game && game.players) && 
        <GameIconAndRecord WinLoss={`${game.players[0]?.score} / ${game.players[1]?.score}`}>
            <EightBallIcon size="small" />
        </GameIconAndRecord> }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search