0

So I have seen people using different ways to declare a function. However, I saw one way that I did not quite understand. The sample code is shown as below:

type Props = { 
    name: string,
    age: number
}

const someFunction = ({
    name,
    age
}: Props) => {
   return (
    // Do something here
   )
}

So I know this code here is first creating a Props object with name and age. The part that I do not get is the part where it shows ({name, age}: Props). I am guessing it is a parameter mapping the state to the props, but I am not sure. Can anyone explain this please?

X_C95
  • 89
  • 1
  • 6
  • 1
    Does this answer your question? [What is destructuring assignment and its uses?](https://stackoverflow.com/questions/54605286/what-is-destructuring-assignment-and-its-uses) – Emile Bergeron Aug 20 '20 at 00:41

1 Answers1

3

It is called Destructuring Assignment. It is an ES6 syntax.

It exists for arrays and objects.

It is basically a way to extract part of an array/object.

When doing { name, age } = props, you're extracting name and age from the usually called props object.

Using destructuring:

const someFunction = ({
    name,
    age
}: Props) => {
  console.log(name, age)
}

Without destructuring:

const someFunction = (props: Props) => {
  const name = props.name
  const age = props.age

  console.log(name, age)  
}
Elfayer
  • 4,411
  • 9
  • 46
  • 76
  • So if I have something like ({"Andy", 10}: Props) it is going to pass it to name = "Andy", age = 10? – X_C95 Aug 20 '20 at 00:41
  • I edited the examples. It is not a way to *assign* values, it is only a shortcut, to avoid having to repeat yourself as in `const name = props.name`. You can simply say: `const { name } = props`. – Elfayer Aug 20 '20 at 00:48
  • That made sense now. Thanks a lot – X_C95 Aug 20 '20 at 03:38