0

I am trying to create a type for an array in React but I am getting the below error. I am not sure what I am missing here.

Could anyone please help me find out the thing I am missing?

Thanks

interface RowsData {
  [key: string]: string | number | JSX.Element;
}

const rows: RowsData = [
  { id: 1, name: 'A', action: <div style={{ color: 'blue' }}> Hello </div> },
  { id: 2, name: 'B', action: <div style={{ color: 'blue' }}> World </div> },
  { id: 3, name: 'C', action: <div style={{ color: 'blue' }}> Foo </div> }
];

Error

Type '{ id: number; name: string; action: JSX.Element; }' is not assignable to type 'string | number | Element'.
  Object literal may only specify known properties, and 'id' does not exist in type 'Element'.ts(2322)
newbie
  • 530
  • 1
  • 9
  • 36
  • 1
    Did you mean `const rows: RowsData[] = [...`? i.e. declaring the type of rows as `RowData[]`, ***not*** `RowsData`. – spender Sep 01 '21 at 12:37

1 Answers1

1

Your typing needs to be changed as,

interface Row {
  id: number;
  name: string;
  action: React.ReactNode;
}

const rows: Row[] = [
  {id: 1, name: 'A', action: <div style={{color: 'blue'}}> Hello </div>},
  {id: 2, name: 'B', action: <div style={{color: 'blue'}}> World </div>},
  {id: 3, name: 'C', action: <div style={{color: 'blue'}}> Foo </div>},
];

Shyam
  • 5,292
  • 1
  • 10
  • 20
  • Damnn... *facepalm* this is what happens when your brain is dead after hours of coding. Thanks a lot man. – newbie Sep 01 '21 at 12:55
  • 1
    I think its time for some rest :-) – Shyam Sep 01 '21 at 12:57
  • Yeah I think the same ;) btw what is the difference between JSX.Element and React.ReactNode and why have you used React.ReactNode? – newbie Sep 01 '21 at 13:39
  • 1
    This should answer your question in much detail - https://stackoverflow.com/questions/58123398/when-to-use-jsx-element-vs-reactnode-vs-reactelement?rq=1 – Shyam Sep 01 '21 at 13:45