typescript - 打字稿所有 lodash/fp 返回类型都是任何
问题描述
我已经安装在一个打字稿项目中:
"@types/lodash": "4.14.150",
"loadash": "4.17.15",
所有数据,在处理lodash/fp
后返回为any
以下代码不报告任何错误:
import {prop} from 'lodash/fp';
const data: { id: string } = { id: 'hello' }
// from the above we know that id is a string, but typing it as a number doesn't report any errors
const meh: number = prop('id')(data)
在不添加类型的情况下number
,我可以看到返回类型是any
请问我该如何解决这个问题?谢谢
解决方案
根据打字稿打字,单字符串参数形式prop()
是:
(path: lodash.PropertyPath): LodashProp8x1;
interface LodashProp8x1 {
(object: null | undefined): undefined;
(object: any): any;
}
所以返回一个返回或prop('id')
返回的函数。undefined
any
似乎官方类型不支持使用此调用签名以类型安全的方式拉出道具。
如果您使用带有两个参数的通用形式之一,并且它的工作方式与您期望的一样:
const meh: number = prop('id', data)
// Type 'string' is not assignable to type 'number'
或者看起来这两个函数语法有一个通用形式,但你必须提前告诉编译器你打算使用的对象类型:
const meh: number = prop<typeof data, 'id'>('id')(data)
// Type 'string' is not assignable to type 'number'
推荐阅读
- sharepoint - SharePoint 2019 抓取错误:首次尝试抓取此对象失败。(无法从 URI 中检索 blob...)
- tensorflow - 用 CNN 预测图像的类别
- r - 如何基于属性生成网络,例如人们列出他们正在参加的活动?
- maven - maven-ear-plugin 从 2 个 webModule 中创建 2 个耳朵(战争)
- python - 日期上传到 Kibana/Elastic 不起作用
- java - 沙盒 Paypal webhook 集成
- regex - 正则表达式:可以出现在两个地方之一的可选子字符串,但不能同时出现
- c# - 在 getter 中返回新结构是否会降低性能?
- css - 图片的 URL 在 CSS 中无法正常工作
- sql - 在 Redshift 中连接字符串的递归 CTE 替代方案