映射对象的函数抛出 "Expected an assignment or function call and instead saw an expression"

Function to map an object throws "Expected an assignment or function call and instead saw an expression"

我在 TypeScript 上有下面这个函数,由于以下错误我无法编译:

Expected an assignment or function call and instead saw an expression

即使在 Stack Overflow 上搜索,我也不太明白为什么。

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

您正在使用名为 Optional chaining 的新 javascript 功能,自 typescript 3.7 起才受支持。确保你的 React 项目中至少有 version 3.7 或更新版本。

请记住,map 用于转换数组,您必须 return 回调中每个项目的值。我在下面的示例中将其更改为 forEach

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;
}

替代方法是使用 filtermap:

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

错误一:没有return值

错误2:'function'是关键字,不能作为标识符

误解:使用 Array.map() 而不是 forEach 和缓冲区变量

误解:使函数参数可为空,而不是期望“未定义”(作用相同)

重构建议:使用过滤器删除不想映射的元素

const mapperFunction = (list?: IListType): AType[] =>
    list?.item.filter(it => it.values && it.values?.key && it.values.value)
              .map(it => ({ attr1: it.name, attr2: it.values.key, attr3: it.values.value }))