【问题标题】:How to provide TypeScript type declarations for modules whose name contains an '@'?如何为名称中包含“@”的模块提供 TypeScript 类型声明?
【发布时间】:2018-10-02 06:50:19
【问题描述】:

我试图通过为我的所有无类型依赖项提供类型声明 (.d.ts) 文件来让 TypeScript 编译器满意。但是,其中一些是流行包的自定义分支,或者像 these 这样的包,它们是更大项目的一部分并共享相同的 @<project-name> 命名空间。在这些情况下,它们的名称将包含@ 字符和斜线,例如@absinthe/socket

在这种情况下,我如何在.t.ds 文件中声明我的类型化模块?对于上面的示例,我尝试了 declare module '@absinthe/socket'declare module 'absinthe__socket'(按照 TypeScript 编译器的建议),但都没有成功。

【问题讨论】:

  • 这个问题看起来很像stackoverflow.com/questions/39235931/…
  • 感谢@artem,确实如此!事实证明这种语法确实有效,我只是在声明文件中错误地放置了import(请参阅下面我自己的答案)。

标签: typescript


【解决方案1】:

Here's another question which describes how to install namespaced packages through @types.

不幸的是,npm 不允许作用域包的名称中包含 @,因此这些名称被修改为使用两个下划线代替 @。

特别是,如果你想为包 @foo/bar 安装类型声明,你需要运行

npm install @types/foo__bar

如果它们不适用于您想要的软件包,make sure your .d.ts file is properly included under your tsconfig.json。例如如果您有"include": ["src/**/*"],请确保.d.ts 文件位于src 文件夹中。

【讨论】:

  • 谢谢@kingdaro!虽然我的问题是关于在 .d.ts 文件中提供 本地 类型,但这确实为那些希望通过 NPM 获取类型的人带来了有用的信息。
【解决方案2】:

原来我在定义文件中错误地导入了另一个模块,但在declare module @absinthe/socket 范围之外。这导致 TS 编译器将文件视为实现,而不是声明文件。像这样在模块声明中移动导入

declare module '@absinthe/socket' { import { Socket as PhoenixSocket } from 'phoenix' … }

解决了我的问题。因此,换句话说,@absinthe/socket 语法在 .d.ts 文件中声明自己的类型时可以正常工作。只有在从 DefinitiveTyped(或另一个 NPM 源)获得这样的声明时,才需要使用双下划线语法 (absinthe__socket)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 2015-07-25
    • 2021-09-07
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多