TypeScript npm typing function change import semantics

When importing a typing file ( .d.ts ) using the import x = require('...') template, the semantics change when package.json typings is used.

For example, the following declaration file is successfully imported when no package.json typings used, but generates error TS2656 ( Exported external package typings file is not a module ) when used with typings :

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

While the same file minus declare module {} successfully imported when used with package.json typings , it generates error TS2307 ( Cannot find module ) when used without writing typings .

 export function myfunc(source: string): string; 

Why change semantics?

It looks like if you are using the new npm typing function, you will have to support the npm and non-npm versions of your typing files.

I hit this while trying to use a typed project file within the project itself (TypeScript is not being viewed in the current package.json project for typings entries, it seems to limit the search to ./node_modules ).

Tested with TypeScript 1.7.5.

+5
source share
1 answer

Per documentation , the typings key in package.json is an analog for the main key, which points to a single Node.js. Thus, it is expected that the d.ts file that d.ts points to will be one declaration of the exported module, not the d.ts package.

Specific rationale given by the documentation:

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

In addition, boot types should not pollute the global area by making potentially conflicting entries from another version of the same library. Modules have their own scope and do not pollute the global namespace; if your typing file is not a module, it will pollute the user's global area and cause conflicts with other packages that depend on your package. Similarly, /// <references ... /> can transfer global declarations to a global scope and should be avoided.

(Personally, like you, I think this implementation is completely wrong and stupid. The typings key should point to a single file containing several relative declare module './foo' { โ€ฆ } describing the entire package as a means pollution prevention file system with tons of TypeScript-specific files. Unfortunately, this ship was sailing at that moment, so your package just needs to have a ton of TypeScript-specific d.ts files next to your JavaScript modules, plus this is an excessive description of the input of the main modules.)

+3
source

Source: https://habr.com/ru/post/1239944/


All Articles