TS2345报错:cType入参箭头函数无法匹配map回调类型求解
TS2345报错原因
该类型不匹配错误的触发逻辑非常明确:
- 你的代码中
orderData被推断/声明为Object[]类型,TypeScript会根据调用map方法的数组类型,自动要求回调函数的入参签名匹配(value: Object, index: number, array: Object[]) => cType - 你传入的
map回调显式将第一个入参item标注为cType类型,和TS要求的Object入参类型不兼容,因此直接抛出类型校验错误 - 额外隐患:当前代码在map回调中直接修改遍历到的原item对象,会污染
orderData原始数据源,后续复用该数据源时可能出现非预期结果。
修复方案
方案1:修正数据源类型(推荐,符合TS规范)
从根源修正类型声明,不需要强制类型断言,同时能获得完整的类型提示,是最优解法:
type cType = { CustomerID: string, ContactName: string, CustomerName: string }; // 显式为orderData、customerData标注正确的数组类型,替换为你实际的数据源赋值逻辑 const orderData: cType[] = []; const customerData: cType[] = []; export const data: cType[] = orderData.map((item) => { // TS会自动推导item为cType,不需要额外类型标注 const matchedCustomer = customerData.find(cItem => cItem.CustomerID === item.CustomerID); // 返回新对象,避免修改原始orderData数据 return { ...item, CustomerName: matchedCustomer?.ContactName ?? '' }; });
Syncfusion的DataGrid组件支持接收结构化子类型数组作为数据源,不需要强制把数据声明为宽泛的Object[],直接传入cType[]类型的data即可正常使用。
方案2:类型断言临时绕过(不推荐)
如果暂时无法调整orderData的全局类型声明,可以通过类型断言跳过该行的TS校验,仅适合快速临时修复:
type cType = { CustomerID: string, ContactName: string, CustomerName: string }; // 将orderData断言为cType[]类型,让TS匹配正确的map回调签名 export const data: Object[] = (orderData as cType[]).map((item: cType) => { let name: cType = (<cType[]>customerData).filter((cItem: cType) => { return cItem.CustomerID === item.CustomerID; })[0]; item.CustomerName = (name || <cType>{}).ContactName; return item; });
注意:该方案只是骗过TS类型检查,不会修复运行时的类型风险,如果orderData里的实际元素不符合cType结构,运行时依然会报错。
内容的提问来源于stack exchange,提问作者NeonH
相关产品推荐
相关产品推荐

