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?
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)
}