cuomo
cuomo

Reputation: 71

Type 'string[] | undefined' is not assignable to type 'string[]'. even though I'm using the ?. (optional)

I've constructed types for my React compoenent props

export type EventObj {
  id: string
  observations?: string[]
  note?: string
}

I use these in my React component like this:

<GameCard 
  id={game.id}
  observations={game.observations} //gets highlighted by TS
  note={game.note} //gets highlighted by TS
/>

Which is defined like this as a component:

const GameCard: React.FC<EventObj> = ({
  id
  observations
  note
}) => {
  return (
   <div>
    <h1>{note}</h1>
    {observations.map(item => <h1>{item}</h1>)}
   </div>
  )
}

The error I'm getting for the highlights at observations and notes is:

Type 'string[] | undefined' is not assignable to type 'string[]'.
  Type 'undefined' is not assignable to type 'string[]'.ts(2322)
App.tsx(16, 3): The expected type comes from property 'observations' which is declared here on type 'IntrinsicAttributes & EventObj & { children?: ReactNode; }'

I've even tried doing observations?: string[] | undefined but that doesn't solve it

Upvotes: 0

Views: 156

Answers (1)

Nick
Nick

Reputation: 16576

If observations could potentially be undefined, you can't just map over it assuming it'll be an array. This is what the compiler is warning you about. Instead, you need to either guard against undefined prior to trying to map, or guard against undefined prior to rendering the entire component (depending on your use case).

In the following example, we make sure observations and note exist before rendering the GameCard:

{game.note && game.observations && <GameCard 
  id={game.id}
  observations={game.observations}
  note={game.note}
/>}

Upvotes: 1

Related Questions