【问题标题】:Typescript all lodash/fp return types are any打字稿所有 lodash/fp 返回类型都是任何
【发布时间】:2023-03-23 22:37:01
【问题描述】:

我已经安装在一个打字稿项目中:

"@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 lodash typescript-typings


    【解决方案1】:

    根据打字稿打字,the single string argument form of prop() is:

    (path: lodash.PropertyPath): LodashProp8x1;
    

    And LodashProp8x1 is:

    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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-29
      • 2020-06-29
      • 2021-09-18
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 2020-11-16
      相关资源
      最近更新 更多