alernerdev
alernerdev

Reputation: 2064

Object destructuring at rest example with multiple arguments

I have a piece of code that looks like this:

onFilterChange = ({name}: {name: string}) => {
    console.log(`entered onFilterChange and name is ${name}` );
}

For this one argument, it compiles and runs.

However, if I was to add another argument:

onFilterChange = ({name}: {name: string}, {value}: {value: string}) => {
   console.log(`entered onFilterChange and name is ${name} and value is ${value}` );
        }

Although it does compile, at run time, there is an error: TypeError: _b is undefined

The function above is invoked as following:

this.props.onChange({name, value});

So am I not seeing something obvious? A few examples on the web that I found all show just one argument -- so it works. THanks

Upvotes: 0

Views: 61

Answers (2)

CRice
CRice

Reputation: 32146

So your signature and the way you invoke the function don't match. You need to do one of either:

// Keep signature and change the way you invoke:
onFilterChange = ({name}: {name: string}, {value}: {value: string})
onFilterChange({name}, {value}) <-- as separate arguments

Or

// Change signature so it takes only one argument:
onFilterChange = ({name, value}: {name: string, value: string})
onFilterChange({name, value}) <-- as single argument

Upvotes: 1

cyr_x
cyr_x

Reputation: 14257

You're using the object destructuring wrongly. Because the function only has one argument, which is an object with the name and the value attribute. Therefore you have to do it like this:

onFilterChange = ({name, value}: {name: string, value: string }) => {
   console.log(`entered onFilterChange and name is ${name} and value is ${value}`);
}

Upvotes: 0

Related Questions