首页 > 解决方案 > 打字稿所有 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

请问我该如何解决这个问题?谢谢

标签: typescriptlodashtypescript-typings

解决方案


根据打字稿打字,单字符串参数形式prop()是:

(path: lodash.PropertyPath): LodashProp8x1;

并且LodashProp8x1是:

interface LodashProp8x1 {
    (object: null | undefined): undefined;
    (object: any): any;
}

所以返回一个返回或prop('id')返回的函数。undefinedany

似乎官方类型不支持使用此调用签名以类型安全的方式拉出道具。

如果您使用带有两个参数的通用形式之一,并且它的工作方式与您期望的一样:

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'

推荐阅读