【发布时间】:2019-12-15 07:15:36
【问题描述】:
我在 TypeScript 应用程序上使用 lodash,但出现错误
无法调用类型缺少调用签名的表达式。输入 '((callbackfn: (value: never, index: number, array: never[]) => U, thisArg?: any) => U[]) | ((callbackfn: (value: Phone, index: number, array: Phone[]) => U, thisArg?: any) => U[])' 没有兼容的调用签名.ts(2349)
功能:
{get(userInfo, 'phone', []).map((item, index) => (
<View style={styles.userPhone} key={index}>
{item.type === 'Desk' && <Text>Phone: {item.num}</Text>}
{item.type === 'Mobile' && <Text>Mobile: {item.num}</Text>}
</View>
))}
如果我这样做,它会正常工作:
{userInfo.phone &&
userInfo.phone.map((item, index) => (
<View style={styles.userPhone} key={index}>
{item.type === 'Desk' && <Text>Phone: {item.num}</Text>}
{item.type === 'Mobile' && <Text>Mobile: {item.num}</Text>}
</View>
))}
那么我会错过什么?
PS:
Lodash get 文档:https://lodash.com/docs/#get
我已经为 lodash 安装了 types 包 -> https://www.npmjs.com/package/@types/lodash
问题是我不能这样做 {userInfo.phone && userInfo.phone.map(...)} 因为我们被强制使用 get 来处理这种类型的事情。
【问题讨论】:
-
请考虑将此代码编辑为minimal reproducible example,如how to ask a good question 指南中所述。理想情况下,代码没有外部依赖项,并且可以在独立 IDE 中演示您的问题,例如 The Playground。
-
如果没有这样一个可重现的例子,我只能猜测什么会解决你的问题,因为我无法测试它。我的猜测:
get(userInfo, 'phone', [] as Phone[])或const noPhones: Phone[] = []; get(userInfo, 'phone', noPhones) -
嗨@jcalz 把它作为答案,所以我可以给你正确的投票。
标签: javascript reactjs typescript ecmascript-6