TypeScript npm typings 功能更改导入语义

标签 typescript

当使用 import x = require('...') 模式导入类型 (.d.ts) 文件时,package.json 中的语义会发生变化 typings 使用条目。

例如下面的声明文件在没有时导入成功 使用了 package.json typings 条目,但它会生成错误 TS2656 (Exported external package typings file is not a module) 使用时 使用 typings 条目:

declare module 'mymodule' {
  export function myfunc(source: string): string;
}

而同一个文件减去 declare module {} 导入成功 当与 package.json typings 条目一起使用时会产生错误 TS2307(找不到模块)在没有 typings 条目的情况下使用。

export function myfunc(source: string): string;

为什么要改变语义?

看起来如果你使用新的 npm typings 功能,你将不得不 维护打字文件的 npm 和非 npm 版本。

我在尝试在 项目本身(TypeScript 不查看当前项目的 typings 条目的 package.json,它似乎限制了它的搜索 到./node_modules).

使用 TypeScript 1.7.5 测试。

最佳答案

根据 the documentation , typings package.json 中的键是 main 的类似物指向单个 Node.js 模块的键。因此,d.ts typings 指向的文件应该是单个导出的模块声明,而不是 d.ts 包。

文档给出的具体理由是:

The rationale is that typings should not bring new compatible sources to the set of compiled files; otherwise source files (i.e. .ts files) will be considered by the compiler as part of the user code and will be compiled, and outputs in the package can be overwritten with the resulting .js outputs.

Additionally, loading typings should not pollute global scope by bringing potentially conflicting entries from different version of the same library. Modules have their own scope, and do not pollute the global namespace, if your typings file is not a module, it will be polluting the user global scope, and will cause conflicts with other packages that depend on your package. Similarly /// <references ... /> can bring global declarations into the global scope and should be avoided.

(就我个人而言,和你一样,我认为这个实现是完全错误和愚蠢的。typings应该指向一个包含多个描述整个包的相关 declare module './foo' { … } 声明的文件,作为避免大量 TypeScript 特定文件污染文件系统的一种方法。不幸的是,这艘船此时已经启航,因此您的包只需要同时包含大量 TypeScript 特定的 d.ts 文件你的 JavaScript 模块,加上这个对主模块输入的冗余描述。)

关于TypeScript npm typings 功能更改导入语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34623590/

相关文章:

visual-studio - 如何阻止 Typescript 编译器在 Visual Studio 2017 中生成 JS 和 JS.MAP 文件?

javascript - 使用扩展运算符更新包含对象的数组

javascript - 如果一个函数组件具有内部可变状态,它可以被认为是纯函数组件吗?

javascript - typescript ,JSON.parse 错误 : "Type ' null' is not assignable to type 'string' .“

angular - Angular 组件中的 DI 错误

angular - Ngrx:如何简化 Action 的定义?

json - 如何在 react typescript 中从 json 文件中获取和显示数据

Javascript 按时间间隔对数组进行分组

typescript - 如何在 TypeScript 中映射类型并添加基于 this 的类型防护?

javascript - NavigationEnd 的 url 属性返回未定义(Angular 6)