Issue
I have this function below on typescript and I cannot compile due to the follwing "Expected an assignment or function call and instead saw an expression". Even searching on SO I don't really understand why yet. Any help is appreciated :)
const function = (list: IListType | undefined) =>{
let listpush: AType[]=[]
list?.item.map(
it =>
{(it.values && it.values?.key && it.values?.value)?
listpush.push({
attr1: it.name,
attr2: it.values.key,
attr3: it.values.value,
}):null
}
)
}
Solution
You are using a new javascript feature called Optional chaining which is only supported since typescript 3.7. Make sure you have at least version 3.7 or newer in your react project.
Keep in mind that map is meant to transform an array, you have to return a value for each item in the callback. I changed it to forEach in the example below:
const myFunction = (list: IListType | undefined) =>{
let listpush: AType[]=[];
list?.item.forEach(it => {
if(it.values && it.values?.key && it.values?.value){
listpush.push({
attr1: it.name,
attr2: it.values.key,
attr3: it.values.value,
})
}
})
return listpush;
}
and alternative would be to use filter and map:
const myFunction = (list: IListType | undefined): AType[] => {
if(!list){
return [];
}
return list.item.filter(it => {
return it.values && it.values?.key && it.values?.value;
}).map(item => ({
attr1: it.name,
attr2: it.values.key,
attr3: it.values.value,
}))
}
Answered By - MaartenDev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.