我已经安装在 typescript 项目中:
"@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
请问我该如何解决这个问题? 谢谢
最佳答案
根据 typescript 打字,the single string argument form of prop()
is:
(path: lodash.PropertyPath): LodashProp8x1;
interface LodashProp8x1 {
(object: null | undefined): undefined;
(object: any): any;
}
因此 prop('id')
返回一个函数,该函数返回 undefined
或 any
。
官方类型似乎不支持使用此调用签名以类型安全的方式拉出 props。
如果您使用带有两个参数的通用形式之一,并且它的工作方式如您所期望的:
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'
关于Typescript 所有 lodash/fp 返回类型都是 any,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61737618/