I am trying to send an simple array of strings to an function that might take no arguments, but Typescript complains with
`Argument of type 'string' is not assignable to parameter of type 'string[] | undefined'`
On the parent I have
// Default array if there is no argument on the submitArray function
const exisistingArray = ['string', 'string', 'string']
// Accept an array otherwise use another exisiting one
const submitArray = (array = exisistingArray) => {
console.log(array)
}
// I then pass the function to the children component
return (
<Component submitArray={submitArray} />
)
And on the component
const data = [{
"first": ['string', 'string', 'string']
},{
"second": ['string', 'string', 'string']
}]
type Props = {
submitArray: (array?: string[]) => void
}
export const Component = ({ submitForm }: Props) => {
return (
<ul>
<li onClick={() => submitArray()>No argument</li>
{ data.map((entry, index) => (
// I get the error here on the argument for the function
<li key={index} onClick={() => submitArray(Object.values(entry)[0])}>
{Object.keys(entry).join()}
</li>
))}
</ul>
)
}
I don't understand why if doing Object.values(entry)[0]
on the data
array, that gives me a plain array of strings, is not working, whereas if I do Object.values(entry)
which is and array of strings inside an array does.
I changed the array to
const data = [{
name: 'first',
values : ['string', 'string', 'string']
},{
name: 'second',
values : ['string', 'string', 'string']
}]
And then it worked well with
export const Component = ({ submitForm }: Props) => {
return (
<ul>
<li onClick={() => submitArray()>No argument</li>
{ data.map((entry, index) => (
<li key={index} onClick={() => submitArray(entry.values)}>
{entry.name)}
</li>
))}
</ul>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.