Irmantas Želionis
Irmantas Želionis

Reputation: 2324

Setting initial state array

I am trying to set initial state with games array like this:

import React from 'react'
import GameList from './GameList'

type GameType =  {
    key : number,
    team1 : string,
    team2 : string
}

interface AppState {
  games: GameType[]
}

class App extends React.Component<{}, AppState {

  constructor(props : {}) {
    super(props)
    this.state = {
      games : [{"key" : 1, "team1" : "AAA", "team2" : "BBB"},
               {"key" : 2, "team1" : "CCC", "team2" : "DDD"}]
      }
  }

  render() {
    return (
      <div className="app">
        <div className="container mt-4">
          <GameList games = {this.state.games} />
        </div>
      </div>
    )
  } 
}

export default App;

when I am sending this state to GameList component it gives me:

Type '{ games: GameType[]; }' is not assignable to type 'IntrinsicAttributes & GameType[]'. Property 'games' does not exist on type 'IntrinsicAttributes & GameType[]

What is the correct way to do this?

Upvotes: 0

Views: 55

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84912

Add an interface (or type if you prefer) describing the full app state, and use that as the second parameter to the generic.

interface AppState {
  games: GameType[]
}

class App extends React.Component<{}, AppState> {

Upvotes: 1

Related Questions