Home > Net >  Why is it needed to nest properties in TS when passing an entire object as a prop in React?
Why is it needed to nest properties in TS when passing an entire object as a prop in React?

Time:08-05

So, let's see the following example, which will throw an error:

interface PersonData {
    name: string
    age: number
    country: string
}

function PersonName({data}: PersonData) {
  return (
    <div>
      <h2>{data.name}</h2>
    </div>
  )
}

The TS error is the following:

Property 'data' does not exist on type 'PersonData'.

And if we nest the properties in the interface then it works. Like so:

interface PersonData {
  data{
    name: string
    age: number
    country: string
  }
}

function PersonName({data}: PersonData) {
  return (
    <div>
      <h2>{data.name}</h2>
    </div>
  )
}

But why? I don't understand the logic.

CodePudding user response:

When you do this, you are destructuring the data property from PersonData, which doesn't exist:

function PersonName({data}: PersonData) {

This is the same as saying:

function PersonName(props: PersonData) {
   const data = props.data;

The reason the update to your interface works is you are explicitly adding a data key to the interface.

Two ways you can fix this, first is to not destructure (notice that data in the function definition is no longer in curly braces):

function PersonName(data: PersonData) {
  return (
    <div>
      <h2>{data.name}</h2>
    </div>
  )
}

The other is to destructure the keys that do exist, like:

function PersonName({ name }: PersonData) {
  return (
    <div>
      <h2>{name}</h2>
    </div>
  )
}

CodePudding user response:

Your code:

interface PersonData {
    name: string
    age: number
    country: string
}

function PersonName({data}: PersonData) {
  return (
    <div>
      <h2>{data.name}</h2>
    </div>
  )
}

Is equivalent to this:

interface PersonData {
    name: string
    age: number
    country: string
}

function PersonName(props: PersonData) {
  const data = props.data;
  return (
    <div>
      <h2>{data.name}</h2>
    </div>
  )
}

CodePudding user response:

interface IProps {
  data: PersonData
}

function PersonName({data}:IProps) {
  return (
    <div>
      <h2>{data.name}</h2>
    </div>
  )
}
  • Related