打字稿推理问题 - 导出函数的返回类型具有或正在使用名称...但无法命名 [英] Typescript inference issue - Return type of exported function has or is using name ... but cannot be named

查看:29
本文介绍了打字稿推理问题 - 导出函数的返回类型具有或正在使用名称...但无法命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,将基于 Promise 的函数(在我的示例中来自 mongodb 节点客户端)转换为 Observable.

I want to create a function which transform a Promise based function, in my example from mongodb node client, into an Observable.

代码很简单

export function updateOneObs(filter: Object, object: Object, collection: Collection<any>) {
    return Observable.fromPromise(collection.updateOne(filter, object));
}

如果我把它放在 VSCode 中,我会收到一条错误消息,内容为

If I put this in VSCode, I get an error message that says

导出函数的返回类型具有或正在使用来自外部模块.../npm-packages/observable-mongo/node_modules/@types/mongodb/index"的名称UpdateWriteOpResult",但无法命名.

为了解决这个问题,我需要通过

To fix this I need to explicitly import the missing type via

import {UpdateWriteOpResult} from 'mongodb';

考虑到错误消息清楚地表明 Typescript 知道在哪里寻找丢失的类型,有没有办法在没有显式导入的情况下通过推理解决问题?

Considering that the error message clearly suggests that Typescript knows where to look for the missing type, is there a way to have resolved via inference without an explicit import?

在我的情况下,导入有一个额外的小缺点:因为我已经用 "noUnusedLocals": true 设置了 Typescript 编译器,一旦我导入丢失的类型,我必须在某处使用它,如果我想避免另一个错误.

In my case the import has ad additional small disadvantage: since I have set up the Typescript compiler with "noUnusedLocals": true, once I import the missing type I have to use it somewhere if I want to avoid another error.

推荐答案

此错误仅在您具有 "declaration": true, 时发生.如果您不需要声明,您可以禁用此选项.如果确实需要声明,则必须为该类型创建本地名称.要生成声明打字稿,需要使用本地名称作为返回类型.编译器知道原始类型所在的位置(正如它在错误中指出的那样),但是要生成声明,它必须在模块中为该类型指定一个别名,这在设计上不会这样做(编译器不在为类型命名的业务,尤其是当您的文件中的其他名称可能存在冲突时)

This error only occurs if you have "declaration": true,. If you don't need declarations you can disable this option. If you do need declarations then you must create local names for the type. To generate declaration typescript will need to use a local name for the return type. The compiler knows where the original type lives (as it points it out in the error), but to generate the declaration it would have to give the type an alias within the module which it will not do by design (the compiler is not in the business giving names to types, especially when there may be conflicts with other names in your file)

这篇关于打字稿推理问题 - 导出函数的返回类型具有或正在使用名称...但无法命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆