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?

1

1 Answer 1

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)  
}
Sign up to request clarification or add additional context in comments.

3 Comments

So if I have something like ({"Andy", 10}: Props) it is going to pass it to name = "Andy", age = 10?
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.
That made sense now. Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.